package com.zscat.mallplus.service.oms.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zscat.mallplus.entity.vo.CartParam;
import com.zscat.mallplus.entity.vo.oms.*;
import com.zscat.mallplus.enums.AllEnum;
import com.zscat.mallplus.enums.OrderStatus;
import com.zscat.mallplus.exception.ApiMallPlusException;
import com.zscat.mallplus.oms.entity.*;
import com.zscat.mallplus.oms.mapper.*;
import com.zscat.mallplus.oms.vo.*;
import com.zscat.mallplus.pms.entity.*;
import com.zscat.mallplus.pms.mapper.PmsFeightTemplateMapper;
import com.zscat.mallplus.pms.mapper.PmsProductMapper;
import com.zscat.mallplus.pms.mapper.PmsSkuStockMapper;
import com.zscat.mallplus.pms.vo.ProductConsultParam;
import com.zscat.mallplus.service.oms.service.*;
import com.zscat.mallplus.service.pms.service.IPmsGiftsService;
import com.zscat.mallplus.service.pms.service.IPmsProductConsultService;
import com.zscat.mallplus.service.pms.service.IPmsProductService;
import com.zscat.mallplus.service.sms.service.*;
import com.zscat.mallplus.service.ums.service.IUmsMemberBlanceLogService;
import com.zscat.mallplus.service.ums.service.IUmsMemberReceiveAddressService;
import com.zscat.mallplus.service.ums.service.IUmsMemberService;
import com.zscat.mallplus.service.ums.service.RedisService;
import com.zscat.mallplus.sms.entity.*;
import com.zscat.mallplus.sms.mapper.*;
import com.zscat.mallplus.sms.vo.SmsCouponHistoryDetail;
import com.zscat.mallplus.sys.entity.SysStore;
import com.zscat.mallplus.sys.mapper.SysStoreMapper;
import com.zscat.mallplus.ums.entity.*;
import com.zscat.mallplus.ums.mapper.UmsIntegrationChangeHistoryMapper;
import com.zscat.mallplus.ums.mapper.UmsIntegrationConsumeSettingMapper;
import com.zscat.mallplus.util.*;
import com.zscat.mallplus.utils.CommonResult;
import com.zscat.mallplus.utils.ValidatorUtils;
import com.zscat.mallplus.vo.ApplyRefundVo;
import com.zscat.mallplus.vo.PageInfo;
import com.zscat.mallplus.vo.Rediskey;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StopWatch;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author zscat
 * @since 2019-04-17
 */
@Service
@Slf4j
public class OmsOrderServiceImpl extends ServiceImpl<OmsOrderMapper, OmsOrder> implements IOmsOrderService {

    @Value(value = "${system.remote.create-public-orders-V1}")
    protected String newCreatePublicOrdersUrl;
    @Resource
    private ISmsGroupActivityService smsGroupActivityService;
    @Resource
    private RedisService redisService;
    @Value("${redis.key.prefix.orderId}")
    private String REDIS_KEY_PREFIX_ORDER_ID;
    @Resource
    private IPmsProductService productService;
    @Resource
    private IUmsMemberReceiveAddressService addressService;
    @Resource
    private IUmsMemberBlanceLogService memberBlanceLogService;

    @Resource
    private IOmsCartItemService cartItemService;

    @Resource
    private IOmsPaymentsService paymentsService;
    @Resource
    private ISmsCouponService couponService;
    @Resource
    private UmsIntegrationConsumeSettingMapper integrationConsumeSettingMapper;
    @Autowired
    private ISmsFlashPromotionProductRelationService smsFlashPromotionProductRelationService;
    @Resource
    private PmsSkuStockMapper skuStockMapper;
    @Resource
    private OmsOrderMapper omsOrderMapper;
    @Resource
    private ISmsCouponHistoryService couponHistoryService;
    @Resource
    private IOmsOrderService orderService;
    @Resource
    private OmsOrderItemMapper omsOrderItemMapper;

    @Resource
    private SmsGroupRecordMapper groupRecordMapper;
    @Autowired
    private IPmsProductConsultService pmsProductConsultService;
    @Resource
    private IOmsOrderItemService orderItemService;
    @Resource
    private OmsOrderMapper orderMapper;
    @Resource
    private SmsGroupMemberMapper groupMemberMapper;
    @Resource
    private IUmsMemberService memberService;
    @Resource
    private OmsOrderSettingMapper orderSettingMapper;
    @Resource
    private OmsCartItemMapper cartItemMapper;
    @Resource
    private SmsGroupMapper groupMapper;
    @Resource
    private IPmsGiftsService giftsService;
    @Resource
    private PmsFeightTemplateMapper pmsFeightTemplateMapper;

    @Resource
    private UmsIntegrationChangeHistoryMapper integrationChangeHistoryMapper;


    @Autowired
    private ISmsBasicGiftsService basicGiftsService;
    @Autowired
    private ISmsBasicMarkingService basicMarkingService;
    @Autowired
    private IOmsOrderOperateHistoryService orderOperateHistoryService;
    @Autowired
    private IPmsGiftsService pmsGiftsService;
    @Resource
    private OmsOrderReturnApplyMapper orderReturnApplyMapper;

    @Resource
    private SmsCouponStoreRelationMapper couponStoreRelationMapper;


    @Resource
    private PmsSkuStockMapper pmsSkuStockMapper;
    @Resource
    private SmsCouponProductRelationMapper smsCouponProductRelationMapper;

    @Resource
    private SmsCouponProductCategoryRelationMapper smsCouponProductCategoryRelationMapper;


    @Resource
    private PmsProductMapper pmsProductMapper;

    @Resource
    private SysStoreMapper sysStoreMapper;

    @Resource
    private OmsSettingShopMapper omsSettingShopMapper;


    @Override
    public int payOrder(TbThanks tbThanks) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(new Date());
        tbThanks.setTime(time);
        tbThanks.setDate(new Date());
        /*TbMember tbMember=tbMemberMapper.selectByPrimaryKey(Long.valueOf(tbThanks.getUserId()));
        if(tbMember!=null){
            tbThanks.setUsername(tbMember.getUsername());
        }
        if(tbThanksMapper.insert(tbThanks)!=1){
            throw new XmallException("保存捐赠支付数据失败");
        }*/

        //设置订单为已付款
        OmsOrder tbOrder = orderMapper.selectById(tbThanks.getOrderId());
        if (tbOrder == null) {
            throw new ApiMallPlusException("订单不存在");
        }
        tbOrder.setStatus(OrderStatus.TO_DELIVER.getValue());
        tbOrder.setPayType(tbThanks.getPayType());
        tbOrder.setPaymentTime(new Date());
        tbOrder.setModifyTime(new Date());
        if (orderMapper.updateById(tbOrder) != 1) {
            throw new ApiMallPlusException("更新订单失败");
        }
        //恢复所有下单商品的锁定库存，扣减真实库存
        OmsOrderItem queryO = new OmsOrderItem();
        queryO.setOrderId(tbThanks.getOrderId());
        List<OmsOrderItem> list = orderItemService.list(new QueryWrapper<>(queryO));

        int count = orderMapper.updateSkuStock(list);
        //发送通知确认邮件
//        String tokenName = UUID.randomUUID().toString();
//        String token = UUID.randomUUID().toString();

        // emailUtil.sendEmailDealThank(EMAIL_SENDER,"【mallcloud商城】支付待审核处理",tokenName,token,tbThanks);
        return count;
    }

    @Override
    public void sendDelayMessageCancelOrder(Long orderId) {
        //获取订单超时时间
        OmsOrderSetting orderSetting = orderSettingMapper.selectById(1L);
        long delayTimes = orderSetting.getNormalOrderOvertime() * 60 * 1000;
        //发送延迟消息
        //  cancelOrderSender.sendMessage(orderId, delayTimes);
    }

    @Override
    public Object preGroupActivityOrder(OrderParam orderParam) {
        SmsGroupActivity smsGroupActivity = smsGroupActivityService.getById(orderParam.getGroupId());
        if (ValidatorUtils.notEmpty(smsGroupActivity.getGoodsIds())) {
            List<PmsProduct> productList = (List<PmsProduct>) productService.listByIds(
                    Arrays.asList(smsGroupActivity.getGoodsIds().split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList()));
            if (productList != null && productList.size() > 0) {
                UmsMember currentMember = memberService.getNewCurrentMember();
                ConfirmOrderResult result = new ConfirmOrderResult();
                // 邮费
                BigDecimal transFee = BigDecimal.ZERO;
                //获取购物车信息
                List<OmsCartItem> list = new ArrayList<>();
                for (PmsProduct product : productList) {
                    if (product.getId() == null)
                        if (product == null) {
                            return new CommonResult().failed("库存不够");
                        }
                    if (product != null && product.getStock() < 1) {
                        return new CommonResult().failed("库存不够");
                    }
                    OmsCartItem omsCartItem = new OmsCartItem();
                    omsCartItem.setProductId(product.getId());
                    omsCartItem.setPrice(product.getPrice());
                    omsCartItem.setChecked(1);
                    omsCartItem.setCreateDate(new Date());
                    omsCartItem.setProductBrand(product.getBrandName());
                    omsCartItem.setProductCategoryId(product.getProductCategoryId());
                    omsCartItem.setProductName(product.getName());
                    omsCartItem.setProductSn(product.getProductSn());
                    omsCartItem.setQuantity(1);
                    omsCartItem.setProductPic(product.getPic());
                    list.add(omsCartItem);
                }
                result.setCartPromotionItemList(list);
                //获取用户收货地址列表
                UmsMemberReceiveAddress queryU = new UmsMemberReceiveAddress();
                if (currentMember == null) {
                    return new CommonResult().fail(100);
                }
                queryU.setMemberId(currentMember.getId());
                List<UmsMemberReceiveAddress> memberReceiveAddressList = addressService.list(new QueryWrapper<>(queryU));
                result.setMemberReceiveAddressList(memberReceiveAddressList);
                UmsMemberReceiveAddress address = addressService.getDefaultItem();
                //获取用户可用优惠券列表
                List<SmsCouponHistoryDetail> couponHistoryDetailList = couponService.listCart(list, 1);
                result.setCouponHistoryDetailList(couponHistoryDetailList);
                //获取用户积分
                result.setMemberIntegration(currentMember.getIntegration());
                result.setBlance(currentMember.getBlance());

                //获取积分使用规则
                UmsIntegrationConsumeSetting integrationConsumeSetting = integrationConsumeSettingMapper.selectById(1L);
                result.setIntegrationConsumeSetting(integrationConsumeSetting);
                //计算总金额、活动优惠、应付金额
                if (list != null && list.size() > 0) {
                    ConfirmOrderResult.CalcAmount calcAmount = calcCartAmount(list, smsGroupActivity.getTransfee(), smsGroupActivity.getPrice());
                    result.setCalcAmount(calcAmount);
                    result.setAddress(address);
                    smsGroupActivity.setProductList(null);
                    result.setGroupActivity(smsGroupActivity);
                    return new CommonResult().success(result);
                }
                return null;
            }
        }
        return null;
    }

    private List<OmsCartItem> goodsToCartList(List<PmsProduct> productList) {
        List<OmsCartItem> cartItems = new ArrayList<>();
        for (PmsProduct product : productList) {
            OmsCartItem omsCartItem = new OmsCartItem();
            omsCartItem.setProductId(product.getId());
            omsCartItem.setPrice(product.getPrice());
            omsCartItem.setChecked(1);
            omsCartItem.setCreateDate(new Date());
            omsCartItem.setProductBrand(product.getBrandName());
            omsCartItem.setProductCategoryId(product.getProductCategoryId());
            omsCartItem.setProductName(product.getName());
            omsCartItem.setProductSn(product.getProductSn());
            omsCartItem.setQuantity(1);
            omsCartItem.setProductPic(product.getPic());
            cartItems.add(omsCartItem);
        }
        return cartItems;
    }

    /**
     * @return
     */
    @Override
    public ConfirmOrderResult submitPreview(OrderParam orderParam) {
        if (ValidatorUtils.empty(orderParam.getTotal())) {
            orderParam.setTotal(1);
        }
        String type = orderParam.getType();
        StopWatch stopWatch = new StopWatch("下单orderType=" + orderParam.getOrderType());
        stopWatch.start("1. 获取购物车商品");
        UmsMember currentMember = memberService.getNewCurrentMember();
        List<OmsCartItem> list = new ArrayList<>();
        if ("3".equals(type)) { // 1 商品详情 2 勾选购物车 3全部购物车的商品
            list = cartItemService.list(currentMember.getId(), null);
        } else if ("1".equals(type)) {
            String cartId = orderParam.getCartId();
            if (org.apache.commons.lang.StringUtils.isBlank(cartId)) {
                throw new ApiMallPlusException("参数为空");
            }
            OmsCartItem omsCartItem = cartItemService.selectById(Long.valueOf(cartId));
            if (omsCartItem == null) {
                return null;
            }
            list.add(omsCartItem);
        } else if ("2".equals(type)) {
            String cart_id_list1 = orderParam.getCartIds();
            if (org.apache.commons.lang.StringUtils.isBlank(cart_id_list1)) {
                throw new ApiMallPlusException("参数为空");
            }
            String[] ids1 = cart_id_list1.split(",");
            List<Long> resultList = new ArrayList<>(ids1.length);
            for (String s : ids1) {
                resultList.add(Long.valueOf(s));
            }
            list = cartItemService.list(currentMember.getId(), resultList);
        } else if ("6".equals(type)) { // 秒杀
            SmsFlashPromotionProductRelation relation = smsFlashPromotionProductRelationService.getById(orderParam.getSkillId());
            PmsProduct product = productService.getById(relation.getProductId());
            OmsCartItem omsCartItem = new OmsCartItem();
            omsCartItem.setQuantity(orderParam.getTotal());
            if (orderParam.getTotal() > relation.getFlashPromotionLimit()) {
                throw new ApiMallPlusException("超过秒杀个数！");
            }
            omsCartItem.setPrice(relation.getFlashPromotionPrice());
            omsCartItem.setProductBrand(product.getBrandId() + "");
            omsCartItem.setProductCategoryId(product.getProductCategoryId());
            omsCartItem.setProductName(product.getName());
            omsCartItem.setProductPic(product.getPic());
            omsCartItem.setProductId(product.getId());
            omsCartItem.setChecked(1);
            omsCartItem.setProductSn(product.getProductSn());

            list.add(omsCartItem);
        }
        if (list == null && list.size() < 1) {
            throw new ApiMallPlusException("订单已提交");
        }
        List<OmsCartItem> newCartList = new ArrayList<>();
        // 取商品大的运费
        BigDecimal transFee = BigDecimal.ZERO;
        for (OmsCartItem cart : list) {
            PmsProduct goods = productService.getById(cart.getProductId());
            if (goods != null && goods.getStock() > 0 && goods.getStock() >= cart.getQuantity()) {
                if (goods.getTransfee().compareTo(transFee) > 0) {
                    transFee = goods.getTransfee();
                }
            }
            newCartList.add(cart);
        }
        stopWatch.stop();
        stopWatch.start("赠品营销计算");
        ConfirmOrderResult result = new ConfirmOrderResult();
        //获取购物车信息
        CartMarkingVo vo = new CartMarkingVo();
        vo.setCartList(newCartList);
        //是否首单
        int firstOrder = orderMapper.selectCount(new QueryWrapper<OmsOrder>().eq("member_id", currentMember.getId()));
        vo.setType(1);
        if (firstOrder > 0) {
            vo.setType(2);
        }
        List<SmsBasicGifts> basicGiftsList = basicGiftsService.matchOrderBasicGifts(vo);
        log.info(com.alibaba.fastjson.JSONObject.toJSONString(basicGiftsList));
        result.setBasicGiftsList(basicGiftsList);
        stopWatch.stop();
        stopWatch.start("其他数据计算");
        result.setCartPromotionItemList(newCartList);
        //获取用户收货地址列表
        UmsMemberReceiveAddress queryU = new UmsMemberReceiveAddress();
        queryU.setMemberId(currentMember.getId());
        List<UmsMemberReceiveAddress> memberReceiveAddressList = addressService.list(new QueryWrapper<>(queryU));
        result.setMemberReceiveAddressList(memberReceiveAddressList);
        UmsMemberReceiveAddress address = addressService.getDefaultItem();
        //获取用户可用优惠券列表
        List<SmsCouponHistoryDetail> couponHistoryDetailList = couponService.listCart(newCartList, 1);
        result.setCouponHistoryDetailList(couponHistoryDetailList);
        //获取用户积分

        result.setBlance(currentMember.getBlance());

        //获取积分使用规则
        UmsIntegrationConsumeSetting integrationConsumeSetting = integrationConsumeSettingMapper.selectOne(new QueryWrapper<>());

        if (integrationConsumeSetting != null && currentMember.getIntegration() > 0) {
            result.setMemberIntegration(currentMember.getIntegration() * integrationConsumeSetting.getMaxPercentPerOrder() / 100);
            result.setIntegrationAmount(BigDecimal.valueOf((currentMember.getIntegration() * integrationConsumeSetting.getMaxPercentPerOrder() / 100 / integrationConsumeSetting.getDeductionPerAmount())));
        }

        //计算总金额、活动优惠、应付金额
        if (list != null && list.size() > 0) {
            ConfirmOrderResult.CalcAmount calcAmount = calcCartAmount(newCartList, transFee, BigDecimal.ZERO);
            result.setCalcAmount(calcAmount);
            result.setAddress(address);
            return result;
        }
        stopWatch.stop();
        log.info(stopWatch.prettyPrint());
        return null;

    }

//    /**
//     * @return
//     */
//    @Override
//    public ConfirmOrderResult submitPreviewV1(SubPreOrderParam subPreOrderParam) {
//        // 数量
//        if (ValidatorUtils.empty(subPreOrderParam.getTotal())) {
//            subPreOrderParam.setTotal(1);
//        }
//        // 类型
//        String type = subPreOrderParam.getType();
//
//        UmsMember currentMember = memberService.getById(subPreOrderParam.getMemberId());
//        // 开始查询购物车商品信息
//        List<OmsCartItem> list = new ArrayList<>();
//        // 1 商品详情 2 勾选购物车 3全部购物车的商品
//        if ("3".equals(type)) {
//            list = cartItemService.list(currentMember.getId(), null);
//        } else if ("1".equals(type)) {
//            String cartId = subPreOrderParam.getCartId();
//            if (org.apache.commons.lang.StringUtils.isBlank(cartId)) {
//                throw new ApiMallPlusException("参数为空");
//            }
//            OmsCartItem omsCartItem = cartItemService.selectById(Long.valueOf(cartId));
//            if (omsCartItem == null) {
//                return null;
//            }
//            list.add(omsCartItem);
//        } else if ("2".equals(type)) {
//            String cart_id_list1 = subPreOrderParam.getCartIds();
//            if (org.apache.commons.lang.StringUtils.isBlank(cart_id_list1)) {
//                throw new ApiMallPlusException("参数为空");
//            }
//            String[] ids1 = cart_id_list1.split(",");
//            List<Long> resultList = new ArrayList<>(ids1.length);
//            for (String s : ids1) {
//                resultList.add(Long.valueOf(s));
//            }
//            list = cartItemService.list(currentMember.getId(), resultList);
//        }
//        // 结束查询购物车商品信息
//        if (list == null && list.size() < 1) {
//            throw new ApiMallPlusException("订单已提交");
//        }
//
//        // 取新的购物车
//        List<OmsCartItem> newCartList = new ArrayList<>();
//        // 取商品大的运费
//        BigDecimal transFee = BigDecimal.ZERO;
//        for (OmsCartItem cart : list) {
//            PmsProduct goods = productService.getById(cart.getProductId());
//            if (goods != null && goods.getStock() > 0 && goods.getStock() >= cart.getQuantity()) {
//                if (goods.getTransfee().compareTo(transFee) > 0) {
//                    // 商品运费
//                    transFee = goods.getTransfee();
//                }
//            }
//            newCartList.add(cart);
//        }
//
//        ConfirmOrderResult result = new ConfirmOrderResult();
//
//        log.info("其他数据计算");
//        result.setCartPromotionItemList(newCartList);
//        //获取用户收货地址列表
//        UmsMemberReceiveAddress queryU = new UmsMemberReceiveAddress();
//        queryU.setMemberId(currentMember.getId());
//        List<UmsMemberReceiveAddress> memberReceiveAddressList = addressService.list(new QueryWrapper<>(queryU));
//        result.setMemberReceiveAddressList(memberReceiveAddressList);
//        UmsMemberReceiveAddress address = addressService.getDefaultItem();
//        //获取用户可用优惠券列表
//        List<SmsCouponHistoryDetail> couponHistoryDetailList = couponService.listCart(newCartList, 1);
//        result.setCouponHistoryDetailList(couponHistoryDetailList);
//
//        //计算总金额、活动优惠、应付金额
//        if (list != null && list.size() > 0) {
//            ConfirmOrderResult.CalcAmount calcAmount = calcCartAmount(newCartList, transFee, BigDecimal.ZERO);
//            result.setCalcAmount(calcAmount);
//            result.setAddress(address);
//            return result;
//        }
//
//        return null;
//    }

    /**
     * 商品详情
     *
     * @return
     */
    @Override
    public ConfirmOrderInfo getSubmitPreviewInfo(SubPreOrderParam subPreOrderParam) {
        OmsCartItem cartItem = new OmsCartItem();
        UmsMember currentMember = memberService.getById(subPreOrderParam.getMemberId());
        PmsProduct pmsProduct = productService.getById(subPreOrderParam.getGoodsId());
        PmsSkuStock pmsSkuStock = skuStockMapper.selectById(subPreOrderParam.getSkuId());
        SysStore sysStore = sysStoreMapper.selectById(pmsProduct.getStoreId());
        //检查商品是否删除、库存不足
        checkGoods(pmsProduct, false, subPreOrderParam.getTotal());
        checkSkuGoods(pmsSkuStock, subPreOrderParam.getTotal());
        ////////////////////////添加到购物车中///////////////////////////////////////////////
        cartItem.setProductId(pmsSkuStock.getProductId());
        cartItem.setMemberId(subPreOrderParam.getMemberId());
        cartItem.setProductSkuId(pmsSkuStock.getId());
        cartItem.setChecked(1);
        cartItem.setPrice(pmsProduct.getPrice());
        cartItem.setProductName(pmsProduct.getName());
        cartItem.setQuantity(subPreOrderParam.getTotal());
        cartItem.setProductPic(pmsProduct.getPic());
        cartItem.setCreateDate(new Date());
        cartItem.setMemberId(subPreOrderParam.getMemberId());
        cartItem.setProductCategoryId(pmsProduct.getProductCategoryId());
        cartItem.setProductBrand(pmsProduct.getBrandName());
        cartItem.setStoreId(pmsProduct.getStoreId());
        cartItem.setStoreName(pmsProduct.getStoreName());
        cartItemMapper.insert(cartItem);
        List<OmsCartItem> newCartList = new ArrayList<>();
        newCartList.add(cartItem);
        ////////////////////////添加到购物车中///////////////////////////////////////////////
        // 开始处理订单页面
        ConfirmOrderInfo result = new ConfirmOrderInfo();
        List<StoreConfirmGoodInfo> storeConfirmGoodInfoList = new ArrayList<>();
        StoreConfirmGoodInfo storeConfirmGoodInfo = new StoreConfirmGoodInfo();
        // 数量
        if (ValidatorUtils.empty(subPreOrderParam.getTotal())) {
            subPreOrderParam.setTotal(1);
        }
        ConfirmOrderGoodInfo confirmOrderGoodInfo = new ConfirmOrderGoodInfo();
        confirmOrderGoodInfo.setProductName(cartItem.getProductName());
        confirmOrderGoodInfo.setProductId(cartItem.getProductId());
        confirmOrderGoodInfo.setProductImage(cartItem.getProductPic());
        confirmOrderGoodInfo.setProductNum(cartItem.getQuantity());
        confirmOrderGoodInfo.setProductPrice(cartItem.getPrice());
        confirmOrderGoodInfo.setSkuId(cartItem.getProductSkuId());
        confirmOrderGoodInfo.setSp(this.getSkuSp(pmsSkuStock));
        List<ConfirmOrderGoodInfo> goods = new ArrayList<>();
        goods.add(confirmOrderGoodInfo);
        //获取用户收货地址列表
        UmsMemberReceiveAddress queryU = new UmsMemberReceiveAddress();
        queryU.setMemberId(currentMember.getId());
        List<UmsMemberReceiveAddress> memberReceiveAddressList = addressService.list(new QueryWrapper<>(queryU));
        result.setMemberReceiveAddressList(memberReceiveAddressList);
        UmsMemberReceiveAddress address = addressService.getDefaultItem();
        result.setMemberReceiveAddressNum(memberReceiveAddressList.size());
        result.setMemberReceiveAddressList(memberReceiveAddressList);
        result.setAddress(address);
        if (address == null) {
            result.setIsHasDefaultAddress(false);
        }
        // 获取店铺信息
        storeConfirmGoodInfo.setStoreId(sysStore.getId().toString());
        storeConfirmGoodInfo.setStoreName(sysStore.getName());
        //获取用户可用优惠券列表
        List<SmsCouponHistoryDetail> couponHistoryDetailList = couponService.listCartV1(newCartList, 1, currentMember.getId());
        storeConfirmGoodInfo.setCouponHistoryDetailList(couponHistoryDetailList);
        storeConfirmGoodInfo.setCouponHistoryNum(couponHistoryDetailList.size());
        // 获取优惠最多的劵
        Long couponId = this.getMostCoupon(newCartList, couponHistoryDetailList, currentMember.getId());
        Long couponHistoryId = this.getMostCouponHistoryId(newCartList, couponHistoryDetailList, currentMember.getId());
        //计算总金额、活动优惠、应付金额、运费
        ConfirmOrderResult.CalcAmount calcAmount = calcCartAllAmount(newCartList, BigDecimal.ZERO, couponId, currentMember.getId());
        storeConfirmGoodInfo.setPayAmount(calcAmount.getPayAmount());
        storeConfirmGoodInfo.setFreightAmount(calcAmount.getFreightAmount());
        storeConfirmGoodInfo.setTotalAmount(calcAmount.getTotalAmount());
        storeConfirmGoodInfo.setPromotionAmount(calcAmount.getPromotionAmount());
        storeConfirmGoodInfo.setGoods(goods);
        storeConfirmGoodInfo.setCouponHistoryId(couponHistoryId);
        storeConfirmGoodInfoList.add(storeConfirmGoodInfo);
        // 封装结果
        result.setStoreConfirmGoodInfoList(storeConfirmGoodInfoList);

        result.setType(subPreOrderParam.getType());
        result.setGoodsId(subPreOrderParam.getGoodsId());
        result.setSkuId(subPreOrderParam.getSkuId());
        result.setTotal(subPreOrderParam.getTotal());


        //计算总金额、活动优惠、应付金额、运费
        ConfirmOrderResult.CalcAmount calcAmount1 = new ConfirmOrderResult.CalcAmount();
        calcAmount1.setPayAmount(BigDecimal.ZERO);
        calcAmount1.setFreightAmount(BigDecimal.ZERO);
        calcAmount1.setPromotionAmount(BigDecimal.ZERO);
        calcAmount1.setTotalAmount(BigDecimal.ZERO);
        for (StoreConfirmGoodInfo storeConfirmGoodInfo1 : storeConfirmGoodInfoList) {
            calcAmount1.setTotalAmount(storeConfirmGoodInfo1.getTotalAmount().add(calcAmount1.getTotalAmount()));
            calcAmount1.setPayAmount(storeConfirmGoodInfo1.getPayAmount().add(calcAmount1.getPayAmount()));
            calcAmount1.setFreightAmount(storeConfirmGoodInfo1.getFreightAmount().add(calcAmount1.getFreightAmount()));
            calcAmount1.setPromotionAmount(storeConfirmGoodInfo1.getPromotionAmount().add(calcAmount1.getPromotionAmount()));
        }

        //
        result.setPayAmount(calcAmount1.getPayAmount());
        result.setTotalAmount(calcAmount1.getTotalAmount());
        result.setFreightAmount(calcAmount1.getFreightAmount());
        result.setPromotionAmount(calcAmount1.getPromotionAmount());
        //
//        result.setPayAmount(calcAmount.getPayAmount());
//        result.setTotalAmount(calcAmount.getTotalAmount());
//        result.setFreightAmount(calcAmount.getFreightAmount());
//        result.setPromotionAmount(calcAmount.getPromotionAmount());
//        //优惠
//        private BigDecimal promotionAmount;
//        //应付金额
//        private BigDecimal payAmount;
//        //订单商品总金额
//        private BigDecimal totalAmount;
        // 删除购物车临时商品
        cartItemMapper.deleteById(cartItem.getId());
        return result;
    }

    private Long getMostCouponHistoryId(List<OmsCartItem> newCartList, List<SmsCouponHistoryDetail> couponHistoryDetailList, Long memberId) {
        Map<Long, BigDecimal> mapPrice = new HashMap<>();
        for (SmsCouponHistoryDetail smsCouponHistoryDetail : couponHistoryDetailList) {
            //  计算优惠金额
            BigDecimal promotionAmount = this.calculationCoupon(newCartList, smsCouponHistoryDetail.getCouponId(), memberId);
            mapPrice.put(smsCouponHistoryDetail.getId(), promotionAmount);
        }
        // 排序
        List<Map.Entry<Long, BigDecimal>> list = new ArrayList<>();

        for (Map.Entry<Long, BigDecimal> entry : mapPrice.entrySet()) {
            //将map中的元素放入list中
            list.add(entry);
        }

        list.sort((o1, o2) -> {
            //逆序（从大到小）排列，正序为“return o1.getValue()-o2.getValue”
            return o2.getValue().compareTo(o1.getValue());
        });
        int i = 0;
        for (Map.Entry<Long, BigDecimal> entry : list) {
            if (i == 0) {
                return entry.getKey();
            }
        }
        return null;
    }


    private Long getMostCoupon(List<OmsCartItem> newCartList, List<SmsCouponHistoryDetail> couponHistoryDetailList, Long memberId) {
        Map<Long, BigDecimal> mapPrice = new HashMap<>();
        for (SmsCouponHistoryDetail smsCouponHistoryDetail : couponHistoryDetailList) {
            //  计算优惠金额
            BigDecimal promotionAmount = this.calculationCoupon(newCartList, smsCouponHistoryDetail.getCouponId(), memberId);
            mapPrice.put(smsCouponHistoryDetail.getCouponId(), promotionAmount);
        }
        // 排序
        List<Map.Entry<Long, BigDecimal>> list = new ArrayList<>();

        for (Map.Entry<Long, BigDecimal> entry : mapPrice.entrySet()) {
            //将map中的元素放入list中
            list.add(entry);
        }

        list.sort((o1, o2) -> {
            //逆序（从大到小）排列，正序为“return o1.getValue()-o2.getValue”
            return o2.getValue().compareTo(o1.getValue());
        });
        int i = 0;
        for (Map.Entry<Long, BigDecimal> entry : list) {
            if (i == 0) {
                return entry.getKey();
            }
        }
        return null;
    }

    /**
     * 全选购物车/勾选购物车
     *
     * @return
     */
    @Override
    public ConfirmOrderInfo getSubmitPreviewInfoV1(SubPreOrderParam subPreOrderParam) {
        ConfirmOrderInfo result = new ConfirmOrderInfo();
        // 数量
        if (ValidatorUtils.empty(subPreOrderParam.getTotal())) {
            subPreOrderParam.setTotal(1);
        }
        UmsMember currentMember = memberService.getById(subPreOrderParam.getMemberId());

        // 查询购物车信息
        String cartIds = subPreOrderParam.getCartIds();
        if (org.apache.commons.lang.StringUtils.isBlank(cartIds)) {
            throw new ApiMallPlusException("参数为空");
        }
        List<OmsCartItem> list;
        // 开始查询购物车商品信息
        String cart_id_list1 = subPreOrderParam.getCartIds();
        if (org.apache.commons.lang.StringUtils.isBlank(cart_id_list1)) {
            throw new ApiMallPlusException("参数为空");
        }
        String[] ids1 = cart_id_list1.split(",");
        List<Long> resultList = new ArrayList<>(ids1.length);
        for (String s : ids1) {
            resultList.add(Long.valueOf(s));
        }
        list = cartItemService.list(currentMember.getId(), resultList);

        // 分店铺
        LinkedHashMap<String, List<OmsCartItem>> map = groupListBySeq(list);
        List<StoreConfirmGoodInfo> storeConfirmGoodInfoList = new ArrayList<>();
        //遍历集合
        for (Map.Entry<String, List<OmsCartItem>> entry : map.entrySet()) {
            StoreConfirmGoodInfo storeConfirmGoodInfo = new StoreConfirmGoodInfo();
            List<OmsCartItem> omsCartItems = entry.getValue();
            log.info("商品列表111：" + omsCartItems);
            List<ConfirmOrderGoodInfo> goods = new ArrayList<>();
            for (OmsCartItem omsCartItem : omsCartItems) {
                // 查询商品信息
                PmsSkuStock pmsSkuStock = pmsSkuStockMapper.selectById(omsCartItem.getProductSkuId());
                ConfirmOrderGoodInfo confirmOrderGoodInfo = new ConfirmOrderGoodInfo();
                confirmOrderGoodInfo.setProductName(omsCartItem.getProductName());
                confirmOrderGoodInfo.setProductId(omsCartItem.getProductId());
                confirmOrderGoodInfo.setProductImage(omsCartItem.getProductPic());
                confirmOrderGoodInfo.setProductNum(omsCartItem.getQuantity());
                confirmOrderGoodInfo.setProductPrice(omsCartItem.getPrice());
                confirmOrderGoodInfo.setSkuId(omsCartItem.getProductSkuId());
                confirmOrderGoodInfo.setSp(this.getSkuSp(pmsSkuStock));
                goods.add(confirmOrderGoodInfo);
            }
            SysStore sysStore = sysStoreMapper.selectById(entry.getKey());
            // 获取店铺信息
            storeConfirmGoodInfo.setStoreId(sysStore.getId().
                    toString());
            storeConfirmGoodInfo.setStoreName(sysStore.getName());
            //获取用户可用优惠券列表
//            List<SmsCouponHistoryDetail> couponHistoryDetailList = couponService.listCartV1(omsCartItems, 1);
            List<SmsCouponHistoryDetail> couponHistoryDetailList = couponService.listCartV1(omsCartItems, 1, currentMember.getId());
            storeConfirmGoodInfo.setCouponHistoryDetailList(couponHistoryDetailList);
            storeConfirmGoodInfo.setCouponHistoryNum(couponHistoryDetailList.size());
            //计算总金额、活动优惠、应付金额、运费
            // 获取优惠最多的劵
            Long couponId = this.getMostCoupon(omsCartItems, couponHistoryDetailList, currentMember.getId());
            Long couponHistoryId = this.getMostCouponHistoryId(omsCartItems, couponHistoryDetailList, currentMember.getId());
            //计算总金额、活动优惠、应付金额、运费
            ConfirmOrderResult.CalcAmount calcAmount = calcCartAllAmount(omsCartItems, BigDecimal.ZERO, couponId, currentMember.getId());
            storeConfirmGoodInfo.setPayAmount(calcAmount.getPayAmount());
            storeConfirmGoodInfo.setFreightAmount(calcAmount.getFreightAmount());
            storeConfirmGoodInfo.setTotalAmount(calcAmount.getTotalAmount());
            storeConfirmGoodInfo.setPromotionAmount(calcAmount.getPromotionAmount());
            storeConfirmGoodInfo.setCartPromotionItemList(omsCartItems);
            storeConfirmGoodInfo.setCouponHistoryId(couponHistoryId);
            // 商品列表
            storeConfirmGoodInfo.setGoods(goods);
            // 添加
            storeConfirmGoodInfoList.add(storeConfirmGoodInfo);
        }
        //result.setStoreConfirmGoodInfoList(storeConfirmGoodInfoList);
        //获取用户收货地址列表
        UmsMemberReceiveAddress queryU = new UmsMemberReceiveAddress();
        queryU.setMemberId(currentMember.getId());
        List<UmsMemberReceiveAddress> memberReceiveAddressList = addressService.list(new QueryWrapper<>(queryU));
        result.setMemberReceiveAddressList(memberReceiveAddressList);
        UmsMemberReceiveAddress address = addressService.getDefaultItem();
        result.setMemberReceiveAddressNum(memberReceiveAddressList.size());
        result.setMemberReceiveAddressList(memberReceiveAddressList);
        result.setAddress(address);
        if (address == null) {
            result.setIsHasDefaultAddress(false);
        }
        // 封装结果
        result.setStoreConfirmGoodInfoList(storeConfirmGoodInfoList);
        // 获取应付金额
        //BigDecimal payAmount = this.getCartPayAmount(result.getStoreConfirmGoodInfoList());


        //计算总金额、活动优惠、应付金额、运费
        ConfirmOrderResult.CalcAmount calcAmount = new ConfirmOrderResult.CalcAmount();
        calcAmount.setPayAmount(BigDecimal.ZERO);
        calcAmount.setFreightAmount(BigDecimal.ZERO);
        calcAmount.setPromotionAmount(BigDecimal.ZERO);
        calcAmount.setTotalAmount(BigDecimal.ZERO);
        for (StoreConfirmGoodInfo storeConfirmGoodInfo : storeConfirmGoodInfoList) {
            calcAmount.setTotalAmount(storeConfirmGoodInfo.getTotalAmount().add(calcAmount.getTotalAmount()));
            calcAmount.setPayAmount(storeConfirmGoodInfo.getPayAmount().add(calcAmount.getPayAmount()));
            calcAmount.setFreightAmount(storeConfirmGoodInfo.getFreightAmount().add(calcAmount.getFreightAmount()));
            calcAmount.setPromotionAmount(storeConfirmGoodInfo.getPromotionAmount().add(calcAmount.getPromotionAmount()));
        }


        //
        result.setPayAmount(calcAmount.getPayAmount());
        result.setTotalAmount(calcAmount.getTotalAmount());
        result.setFreightAmount(calcAmount.getFreightAmount());
        result.setPromotionAmount(calcAmount.getPromotionAmount());
        //result.setPayAmount(payAmount);
        return result;
    }

    /**
     * 获取多个店铺总的金额
     *
     * @return
     */
    private BigDecimal getCartPayAmount(List<StoreConfirmGoodInfo> storeConfirmGoodInfoList) {
        BigDecimal payAmount = BigDecimal.ZERO;
        for (StoreConfirmGoodInfo storeConfirmGoodInfo : storeConfirmGoodInfoList) {
            payAmount = payAmount.subtract(storeConfirmGoodInfo.getPayAmount());
        }
        return payAmount;
    }

    /**
     * @return
     */
    public ConfirmOrderInfo getSubmitPreviewInfoV2(SubPreOrderParam subPreOrderParam) {
        ConfirmOrderInfo result = new ConfirmOrderInfo();
        List<StoreConfirmGoodInfo> storeConfirmGoodInfoList = new ArrayList<>();
        StoreConfirmGoodInfo storeConfirmGoodInfo = new StoreConfirmGoodInfo();
        // 数量
        if (ValidatorUtils.empty(subPreOrderParam.getTotal())) {
            subPreOrderParam.setTotal(1);
        }
        UmsMember currentMember = memberService.getById(subPreOrderParam.getMemberId());

        // 查询购物车信息
        OmsCartItem omsCartItem;
        String cartId = subPreOrderParam.getCartId();
        if (org.apache.commons.lang.StringUtils.isBlank(cartId)) {
            throw new ApiMallPlusException("参数为空");
        }
        omsCartItem = cartItemService.selectById(Long.valueOf(cartId));
        if (omsCartItem == null) {
            throw new ApiMallPlusException("订单已提交");
        }
        if (omsCartItem == null) {
            throw new ApiMallPlusException("订单已提交");
        }
        List<OmsCartItem> newCartList = new ArrayList<>();
        newCartList.add(omsCartItem);
        // 查询商品信息
        PmsSkuStock pmsSkuStock = pmsSkuStockMapper.selectById(omsCartItem.getProductSkuId());
        PmsProduct pmsProduct = pmsProductMapper.selectById(omsCartItem.getProductId());
        ConfirmOrderGoodInfo confirmOrderGoodInfo = new ConfirmOrderGoodInfo();
        confirmOrderGoodInfo.setProductName(omsCartItem.getProductName());
        confirmOrderGoodInfo.setProductId(omsCartItem.getProductId());
        confirmOrderGoodInfo.setProductImage(omsCartItem.getProductPic());
        confirmOrderGoodInfo.setProductNum(omsCartItem.getQuantity());
        confirmOrderGoodInfo.setProductPrice(omsCartItem.getPrice());
        confirmOrderGoodInfo.setSkuId(omsCartItem.getProductSkuId());
        confirmOrderGoodInfo.setSp(this.getSkuSp(pmsSkuStock));
        SysStore sysStore = sysStoreMapper.selectById(pmsProduct.getStoreId());
        // 查询运费
        BigDecimal transFee = BigDecimal.ZERO;
        //获取用户收货地址列表
        UmsMemberReceiveAddress queryU = new UmsMemberReceiveAddress();
        queryU.setMemberId(currentMember.getId());
        List<UmsMemberReceiveAddress> memberReceiveAddressList = addressService.list(new QueryWrapper<>(queryU));
        result.setMemberReceiveAddressList(memberReceiveAddressList);
        UmsMemberReceiveAddress address = addressService.getDefaultItem();
        result.setMemberReceiveAddressNum(memberReceiveAddressList.size());
        result.setMemberReceiveAddressList(memberReceiveAddressList);
        result.setAddress(address);
        if (address == null) {
            result.setIsHasDefaultAddress(false);
        }
        // 获取店铺信息
        storeConfirmGoodInfo.setStoreId(sysStore.getId().toString());
        storeConfirmGoodInfo.setStoreName(sysStore.getName());
        //获取用户可用优惠券列表
        List<SmsCouponHistoryDetail> couponHistoryDetailList = couponService.listCart(newCartList, 1);
        storeConfirmGoodInfo.setCouponHistoryDetailList(couponHistoryDetailList);
        storeConfirmGoodInfo.setCouponHistoryNum(couponHistoryDetailList.size());
        //计算总金额、活动优惠、应付金额、运费
        ConfirmOrderResult.CalcAmount calcAmount = calcCartAmount(newCartList, transFee, BigDecimal.ZERO);
        storeConfirmGoodInfo.setPayAmount(calcAmount.getPayAmount());
        storeConfirmGoodInfo.setFreightAmount(calcAmount.getFreightAmount());
        storeConfirmGoodInfo.setTotalAmount(calcAmount.getTotalAmount());
        storeConfirmGoodInfo.setPromotionAmount(calcAmount.getPromotionAmount());
        // 封装结果
        storeConfirmGoodInfoList.add(storeConfirmGoodInfo);
        result.setStoreConfirmGoodInfoList(storeConfirmGoodInfoList);
        return result;
    }

    /**
     * 购物车分店铺
     *
     * @param list
     * @return
     */
    private LinkedHashMap<String, List<OmsCartItem>> groupListBySeq(List<OmsCartItem> list) {

        LinkedHashMap<String, List<OmsCartItem>> map = new LinkedHashMap<>();
        for (OmsCartItem bean : list) {
            log.info("店铺id:" + bean.getStoreId());
            log.info("店铺map:" + map.toString());
            log.info("店铺map111:" + map.get(bean.getStoreId().toString()));
            if (map.get(bean.getStoreId().toString()) != null && map.size() > 0) {
                List<OmsCartItem> subList = map.get(bean.getStoreId().toString());
                log.info("subList数组：" + subList);
                subList.add(bean);
                log.info("subList数组11：" + subList);
                map.put(bean.getStoreId().toString(), subList);
            } else {
                List<OmsCartItem> subList = new ArrayList<>();
                subList.add(bean);
                map.put(bean.getStoreId().toString(), subList);
                log.info("店铺map222:" + map.get(bean.getStoreId()));
            }
        }
        return map;
    }


    private String getSkuSp(PmsSkuStock pmsSkuStock) {
        String s = "";
        if (pmsSkuStock.getSp1() != null) {
            s = s + pmsSkuStock.getSp1() + "";
        }
        if (pmsSkuStock.getSp2() != null) {
            s = s + pmsSkuStock.getSp2() + "";
        }
        if (pmsSkuStock.getSp3() != null) {
            s = s + pmsSkuStock.getSp3() + "";
        }
        if (pmsSkuStock.getSp4() != null) {
            s = s + pmsSkuStock.getSp4() + "";
        }
        return s;
    }

    /**
     * @return
     */
    @Override
    public ConfirmListOrderResult submitStorePreview(OrderParam orderParam) {
        ConfirmListOrderResult confirmListOrderResult = new ConfirmListOrderResult();
        List<ConfirmOrderResult> confirmOrderResultList = new ArrayList<>();
        if (ValidatorUtils.empty(orderParam.getTotal())) {
            orderParam.setTotal(1);
        }

        UmsMember currentMember = memberService.getNewCurrentMember();
        List<OmsCartItem> list = new ArrayList<>();

        String cart_id_list1 = orderParam.getCartIds();
        if (org.apache.commons.lang.StringUtils.isBlank(cart_id_list1)) {
            throw new ApiMallPlusException("参数为空");
        }
        String[] ids1 = cart_id_list1.split(",");
        List<Long> resultList = new ArrayList<>(ids1.length);
        for (String s : ids1) {
            resultList.add(Long.valueOf(s));
        }
        list = cartItemService.list(currentMember.getId(), resultList);

        if (list == null && list.size() < 1) {
            throw new ApiMallPlusException("订单已提交");
        }
        BigDecimal totalPayAmount = BigDecimal.ZERO;
        Map<Integer, List<OmsCartItem>> map = list.stream().collect(Collectors.groupingBy(OmsCartItem::getStoreId));
        if (map.size() > 1) {
            for (Map.Entry<Integer, List<OmsCartItem>> entry : map.entrySet()) {
                List<OmsCartItem> subList = entry.getValue();
                List<OmsCartItem> newCartList = new ArrayList<>();
                // 取商品大的运费
                BigDecimal transFee = BigDecimal.ZERO;
                ConfirmOrderResult result = new ConfirmOrderResult();
                for (OmsCartItem cart : subList) {
                    PmsProduct goods = productService.getById(cart.getProductId());
                    if (goods != null && goods.getStock() > 0 && goods.getStock() >= cart.getQuantity()) {
                        if (goods.getTransfee().compareTo(transFee) > 0) {
                            transFee = goods.getTransfee();
                        }
                    }
                    newCartList.add(cart);
                    result.setStoreName(cart.getStoreName());
                }


                //获取购物车信息
                CartMarkingVo vo = new CartMarkingVo();
                vo.setCartList(newCartList);
                //是否首单
                int firstOrder = orderMapper.selectCount(new QueryWrapper<OmsOrder>().eq("member_id", currentMember.getId()));
                vo.setType(1);
                if (firstOrder > 0) {
                    vo.setType(2);
                }
                List<SmsBasicGifts> basicGiftsList = basicGiftsService.matchOrderBasicGifts(vo);
                result.setBasicGiftsList(basicGiftsList);
                result.setCartPromotionItemList(newCartList);

                //获取用户可用优惠券列表
                List<SmsCouponHistoryDetail> couponHistoryDetailList = couponService.listCart(newCartList, 1);
                result.setCouponHistoryDetailList(couponHistoryDetailList);

                //计算总金额、活动优惠、应付金额
                if (newCartList != null && newCartList.size() > 0) {
                    ConfirmOrderResult.CalcAmount calcAmount = calcCartAmount(newCartList, transFee, BigDecimal.ZERO);
                    result.setCalcAmount(calcAmount);
                    confirmOrderResultList.add(result);
                    totalPayAmount = totalPayAmount.add(result.getCalcAmount().getPayAmount());
                }

            }
        }
        confirmListOrderResult.setConfirmOrderResultList(confirmOrderResultList);
        //获取用户收货地址列表
        UmsMemberReceiveAddress queryU = new UmsMemberReceiveAddress();
        queryU.setMemberId(currentMember.getId());
        List<UmsMemberReceiveAddress> memberReceiveAddressList = addressService.list(new QueryWrapper<>(queryU));
        confirmListOrderResult.setMemberReceiveAddressList(memberReceiveAddressList);
        UmsMemberReceiveAddress address = addressService.getDefaultItem();
        confirmListOrderResult.setAddress(address);
        confirmListOrderResult.setBlance(currentMember.getBlance());
        confirmListOrderResult.setTotalPayAmount(totalPayAmount);
        return confirmListOrderResult;

    }

    @Override
    public CommonResult generateOrder(OrderParam orderParam) {
        if (ValidatorUtils.empty(orderParam.getTotal())) {
            orderParam.setTotal(1);
        }
        String type = orderParam.getType();
        UmsMember currentMember = memberService.getNewCurrentMember();
        OmsOrder order = new OmsOrder();
        // 1. 获取购物车商品
        List<OmsCartItem> cartPromotionItemList = new ArrayList<>();
        StopWatch stopWatch = new StopWatch("下单orderType=" + orderParam.getOrderType());
        stopWatch.start("1. 获取购物车商品");
        if (ValidatorUtils.empty(orderParam.getAddressId())) {
            return new CommonResult().failed("address is null");
        }
        //团购订单
        SmsGroupActivity smsGroupActivity = null;
        if (orderParam.getOrderType() == 3) {
            smsGroupActivity = smsGroupActivityService.getById(orderParam.getGroupActivityId());
            if (ValidatorUtils.notEmpty(smsGroupActivity.getGoodsIds())) {
                List<PmsProduct> productList = (List<PmsProduct>) productService.listByIds(
                        Arrays.asList(smsGroupActivity.getGoodsIds().split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList()));
                if (productList != null && productList.size() > 0) {
                    order.setFreightAmount(smsGroupActivity.getTransfee());
                    //获取购物车信息
                    cartPromotionItemList = goodsToCartList(productList);
                }
            }
        } else {
            if ("3".equals(type)) { // 1 商品详情 2 勾选购物车 3全部购物车的商品
                cartPromotionItemList = cartItemService.listPromotion(currentMember.getId(), null);
            }
            if ("1".equals(type)) {
                Long cartId = Long.valueOf(orderParam.getCartId());
                OmsCartItem omsCartItem = cartItemService.selectById(cartId);
                List<OmsCartItem> list = new ArrayList<>();
                if (omsCartItem != null) {
                    list.add(omsCartItem);
                } else {
                    throw new ApiMallPlusException("订单已提交");
                }
                if (!CollectionUtils.isEmpty(list)) {
                    cartPromotionItemList = cartItemService.calcCartPromotion(list);
                }
            } else if ("2".equals(type)) {
                String cart_id_list1 = orderParam.getCartIds();
                String[] ids1 = cart_id_list1.split(",");
                List<Long> resultList = new ArrayList<>(ids1.length);
                for (String s : ids1) {
                    resultList.add(Long.valueOf(s));
                }
                cartPromotionItemList = cartItemService.listPromotion(currentMember.getId(), resultList);
            } else if ("6".equals(type)) { // 秒杀
                SmsFlashPromotionProductRelation relation = smsFlashPromotionProductRelationService.getById(orderParam.getSkillId());
                PmsProduct product = productService.getById(relation.getProductId());
                OmsCartItem omsCartItem = new OmsCartItem();
                omsCartItem.setQuantity(orderParam.getTotal());
                if (orderParam.getTotal() > relation.getFlashPromotionLimit()) {
                    throw new ApiMallPlusException("超过秒杀个数！");
                }
                omsCartItem.setPrice(relation.getFlashPromotionPrice());
                omsCartItem.setProductBrand(product.getBrandId() + "");
                omsCartItem.setProductCategoryId(product.getProductCategoryId());
                omsCartItem.setProductName(product.getName());
                omsCartItem.setProductPic(product.getPic());
                omsCartItem.setProductId(product.getId());
                omsCartItem.setChecked(1);
                omsCartItem.setProductSn(product.getProductSn());

                cartPromotionItemList.add(omsCartItem);
            }
        }
        stopWatch.stop();
        if (cartPromotionItemList == null || cartPromotionItemList.size() < 1) {
            return new CommonResult().failed("没有下单的商品");
        }
        List<OmsOrderItem> orderItemList = new ArrayList<>();
        //获取购物车及优惠信息
        String name = "";
        BigDecimal transFee = BigDecimal.ZERO;
        List<OmsCartItem> newCartItemList = new ArrayList<>();
        Integer isFirst = 1;
        stopWatch.start("2. 校验商品库存，舍弃商品不存或没有库存 计算运费");
        // 2. 校验商品库存，舍弃商品不存或没有库存 计算运费
        for (OmsCartItem cartPromotionItem : cartPromotionItemList) {
            boolean flag = false;
            PmsProduct goods = productService.getById(cartPromotionItem.getProductId());
            if (!ValidatorUtils.empty(cartPromotionItem.getProductSkuId()) && cartPromotionItem.getProductSkuId() > 0) {
                if (goods != null && goods.getId() != null && goods.getStock() > 0 && goods.getStock() > cartPromotionItem.getQuantity()) {
                    PmsSkuStock skuStock = skuStockMapper.selectById(cartPromotionItem.getProductSkuId());
                    if (skuStock.getStock() > 0 && skuStock.getStock() >= cartPromotionItem.getQuantity()) {
                        flag = true;
                    }
                }
            } else {
                if (goods != null && goods.getId() != null && goods.getStock() > 0 && goods.getStock() >= cartPromotionItem.getQuantity()) {
                    flag = true;
                }
            }
            if (flag) {
                if (goods.getTransfee().compareTo(transFee) > 0) {
                    transFee = goods.getTransfee();
                }
                //生成下单商品信息
                OmsOrderItem orderItem = createOrderItem(cartPromotionItem);
                orderItem.setType(AllEnum.OrderItemType.GOODS.code());
                orderItemList.add(orderItem);
                if (isFirst == 1) {
                    name = cartPromotionItem.getProductName();
                    order.setGoodsId(cartPromotionItem.getProductId());
                    order.setGoodsName(cartPromotionItem.getProductName());
                }

                newCartItemList.add(cartPromotionItem);
            }
        }
        if (newCartItemList == null || newCartItemList.size() < 1) {
            return new CommonResult().failed("没有下单的商品");
        }

        //3.计算优惠券
        SmsCouponHistory couponHistory = new SmsCouponHistory();
        SmsCoupon coupon = null;
        if (orderParam.getCouponId() != null) {
            //   couponHistory = couponHistoryService.getById(orderParam.getMemberCouponId());
            coupon = couponService.getById(orderParam.getCouponId());
        }
        UmsMemberReceiveAddress address = addressService.getById(orderParam.getAddressId());
        //根据商品合计、运费、活动优惠、优惠券、积分计算应付金额

        createOrderObj(order, orderParam, currentMember, orderItemList, address);
        if (smsGroupActivity != null) {
            order.setTotalAmount(smsGroupActivity.getPrice());
        }
        if (orderParam.getOrderType() != 3) {
            order.setFreightAmount(transFee);
        }
        if (orderParam.getCouponId() == null || orderParam.getCouponId() == 0) {
            order.setCouponAmount(new BigDecimal(0));
        } else {
            order.setCouponId(orderParam.getCouponId());
            order.setCouponAmount(coupon.getAmount());
        }
        //获取积分使用规则
       /* UmsIntegrationConsumeSetting integrationConsumeSetting = integrationConsumeSettingMapper.selectOne(new QueryWrapper<>());

        if (integrationConsumeSetting!=null && currentMember.getIntegration()>0){
            order.setUseIntegration(currentMember.getIntegration()*integrationConsumeSetting.getMaxPercentPerOrder()/100);
            order.setIntegrationAmount(BigDecimal.valueOf((currentMember.getIntegration()*integrationConsumeSetting.getMaxPercentPerOrder()/100/integrationConsumeSetting.getDeductionPerAmount())));
        }*/
        CartMarkingVo vo = new CartMarkingVo();
        vo.setCartList(newCartItemList);
        SmsBasicMarking basicMarking = basicMarkingService.matchOrderBasicMarking(vo);
        log.info("basicMarking=" + com.alibaba.fastjson.JSONObject.toJSONString(basicMarking));
        if (basicMarking != null) {
            order.setPromotionAmount(basicMarking.getMinAmount());
        }
        order.setPayAmount(calcPayAmount(order));
        if (order.getPayAmount().compareTo(BigDecimal.ZERO) < 0) {
            order.setPayAmount(new BigDecimal("0.01"));
        }
        stopWatch.stop();

        stopWatch.start("3.计算赠品营销");
        if (ValidatorUtils.notEmpty(orderParam.getBasicGiftsVar())) {
            String[] basicGiftsList = orderParam.getBasicGiftsVar().split("@");
            if (basicGiftsList != null && basicGiftsList.length > 0) {
                for (String basicGifts : basicGiftsList) {
                    if (ValidatorUtils.notEmpty(basicGifts)) {
                        String[] beanKv = basicGifts.split(":");
                        if (beanKv != null && beanKv.length > 1) {
                            String[] ids = beanKv[1].split(",");
                            if (ids != null && ids.length > 0) {
                                for (String id : ids) {
                                    PmsGifts pmsGifts = pmsGiftsService.getById(id);
                                    if (pmsGifts != null) {
                                        OmsOrderItem orderItem = new OmsOrderItem();
                                        orderItem.setOrderSn(beanKv[0]);
                                        orderItem.setProductId(pmsGifts.getId());
                                        orderItem.setProductName(pmsGifts.getTitle());
                                        orderItem.setProductPic(pmsGifts.getIcon());
                                        orderItem.setProductPrice(pmsGifts.getPrice());
                                        orderItem.setProductQuantity(1);
                                        orderItem.setType(AllEnum.OrderItemType.GIFT.code());

                                        orderItemList.add(orderItem);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        stopWatch.stop();
        stopWatch.start("4.计算优惠券 插入订单");
        // TODO: 2018/9/3 bill_*,delivery_*
        //插入order表和order_item表
        orderService.save(order);
        for (OmsOrderItem orderItem : orderItemList) {
            orderItem.setOrderId(order.getId());
            orderItem.setOrderSn(order.getOrderSn());
            if (ValidatorUtils.notEmpty(orderParam.getSkillId())) {
                orderItem.setGiftIntegration(orderParam.getSkillId().intValue());
            }
        }
        orderItemService.saveBatch(orderItemList);
        //如使用优惠券更新优惠券使用状态
        if (orderParam.getCouponId() != null && orderParam.getCouponId() > 0) {
            couponHistory.setId(orderParam.getMemberCouponId());
            couponHistory.setUseStatus(1);
            couponHistory.setUseTime(new Date());
            couponHistory.setOrderId(order.getId());
            couponHistory.setOrderSn(order.getOrderSn());
            couponHistoryService.updateById(couponHistory);
        }
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(order.getId());
        history.setCreateTime(new Date());
        history.setOperateMan("shop");
        history.setPreStatus(-1);
        history.setOrderStatus(OrderStatus.INIT.getValue());
        history.setNote("创建订单");
        orderOperateHistoryService.save(history);
        stopWatch.stop();
        //如使用积分需要扣除积分
        if (order.getUseIntegration() != null) {
            memberService.updateIntegration(currentMember.getId(), currentMember.getIntegration() - order.getUseIntegration());
        }
        stopWatch.start("5.锁库存 删除购物车");
        lockStockByOrder(orderItemList, type);
        //删除购物车中的下单商品
        deleteCartItemList(cartPromotionItemList, currentMember);
        Map<String, Object> result = new HashMap<>();
        result.put("order", order);
        result.put("orderItemList", orderItemList);
        stopWatch.stop();
        if (ValidatorUtils.empty(orderParam.getFormId())) {
            stopWatch.start("5.小程序推送消息");
            push(currentMember, order, orderParam.getPage(), orderParam.getFormId(), name);
            stopWatch.stop();
        }
        log.info(stopWatch.prettyPrint());
        return new CommonResult().success("下单成功", result);
    }

//    @Override
//    public CommonResult generateOrderV1(OrderParam orderParam) {
//        if (ValidatorUtils.empty(orderParam.getTotal())) {
//            orderParam.setTotal(1);
//        }
//        // 订单类型
//        String type = orderParam.getType();
//        if (ValidatorUtils.empty(orderParam.getMemberId())) {
//            return new CommonResult().failed("memberId is null");
//        }
//        UmsMember currentMember = memberService.getById(orderParam.getMemberId());
//        OmsOrder order = new OmsOrder();
//        // 1. 获取购物车商品
//        List<OmsCartItem> cartPromotionItemList = new ArrayList<>();
//        StopWatch stopWatch = new StopWatch("下单orderType=" + orderParam.getOrderType());
//        stopWatch.start("1. 获取购物车商品");
//        if (ValidatorUtils.empty(orderParam.getAddressId())) {
//            return new CommonResult().failed("address is null");
//        }
//        // 1 商品详情 2 勾选购物车 3全部购物车的商品
//        if ("3".equals(type)) { // 3全部购物车的商品
//            cartPromotionItemList = cartItemService.listPromotion(currentMember.getId(), null);
//        } else if ("1".equals(type)) { // 1 商品详情
//            // 获取购物车里的商品
//            Long cartId = Long.valueOf(orderParam.getCartId());
//            OmsCartItem omsCartItem = cartItemService.selectById(cartId);
//            List<OmsCartItem> list = new ArrayList<>();
//            if (omsCartItem != null) {
//                list.add(omsCartItem);
//            } else {
//                throw new ApiMallPlusException("订单已提交");
//            }
//            if (!CollectionUtils.isEmpty(list)) {
//                cartPromotionItemList = cartItemService.calcCartPromotion(list);
//            }
//        } else if ("2".equals(type)) {// 2 勾选购物车
//            String cart_id_list1 = orderParam.getCartIds();
//            String[] ids1 = cart_id_list1.split(",");
//            List<Long> resultList = new ArrayList<>(ids1.length);
//            for (String s : ids1) {
//                resultList.add(Long.valueOf(s));
//            }
//            cartPromotionItemList = cartItemService.listPromotion(currentMember.getId(), resultList);
//        }
//        stopWatch.stop();
//        if (cartPromotionItemList == null || cartPromotionItemList.size() < 1) {
//            return new CommonResult().failed("没有下单的商品");
//        }
//
//        //2、获取购物车及优惠信息
//        List<OmsOrderItem> orderItemList = new ArrayList<>();
//        // 运费
//        BigDecimal transFee = BigDecimal.ZERO;
//        List<OmsCartItem> newCartItemList = new ArrayList<>();
//        stopWatch.start("3. 校验商品库存，舍弃商品不存或没有库存 计算运费");
//        // 3. 校验商品库存，舍弃商品不存在或没有库存 计算运费
//        for (OmsCartItem cartPromotionItem : cartPromotionItemList) {
//            boolean flag = false;
//            PmsProduct goods = productService.getById(cartPromotionItem.getProductId());
//            if (!ValidatorUtils.empty(cartPromotionItem.getProductSkuId()) && cartPromotionItem.getProductSkuId() > 0) {
//                if (goods != null && goods.getId() != null && goods.getStock() > 0 && goods.getStock() > cartPromotionItem.getQuantity()) {
//                    PmsSkuStock skuStock = skuStockMapper.selectById(cartPromotionItem.getProductSkuId());
//                    if (skuStock.getStock() > 0 && skuStock.getStock() >= cartPromotionItem.getQuantity()) {
//                        flag = true;
//                    }
//                }
//            } else {
//                if (goods != null && goods.getId() != null && goods.getStock() > 0 && goods.getStock() >= cartPromotionItem.getQuantity()) {
//                    flag = true;
//                }
//            }
//            if (flag) {
//                if (goods.getTransfee().compareTo(transFee) > 0) {
//                    transFee = goods.getTransfee();
//                }
//                //生成下单商品信息
//                OmsOrderItem orderItem = createOrderItem(cartPromotionItem);
//                orderItem.setType(AllEnum.OrderItemType.GOODS.code());
//                orderItemList.add(orderItem);
//                newCartItemList.add(cartPromotionItem);
//            }
//        }
//        if (newCartItemList == null || newCartItemList.size() < 1) {
//            return new CommonResult().failed("没有下单的商品");
//        }
//
//        //3.计算优惠券
//        SmsCouponHistory couponHistory = new SmsCouponHistory();
//        SmsCoupon coupon = null;
//        if (orderParam.getCouponId() != null) {
//            //   couponHistory = couponHistoryService.getById(orderParam.getMemberCouponId());
//            coupon = couponService.getById(orderParam.getCouponId());
//        }
//        UmsMemberReceiveAddress address = addressService.getById(orderParam.getAddressId());
//        //根据商品合计、运费、活动优惠、优惠券、积分计算应付金额
//        createOrderObj(order, orderParam, currentMember, orderItemList, address);
//        if (orderParam.getOrderType() != 3) {
//            order.setFreightAmount(transFee);
//        }
//        if (orderParam.getCouponId() == null || orderParam.getCouponId() == 0) {
//            order.setCouponAmount(new BigDecimal(0));
//        } else {
//            order.setCouponId(orderParam.getCouponId());
//            order.setCouponAmount(coupon.getAmount());
//        }
//        order.setPayAmount(calcPayAmount(order));
//        if (order.getPayAmount().compareTo(BigDecimal.ZERO) < 0) {
//            order.setPayAmount(new BigDecimal("0.01"));
//        }
//        stopWatch.stop();
//
//        stopWatch.start("4.计算优惠券 插入订单");
//        //插入order表和order_item表
//        orderService.save(order);
//        for (OmsOrderItem orderItem : orderItemList) {
//            orderItem.setOrderId(order.getId());
//            orderItem.setOrderSn(order.getOrderSn());
//            if (ValidatorUtils.notEmpty(orderParam.getSkillId())) {
//                orderItem.setGiftIntegration(orderParam.getSkillId().intValue());
//            }
//        }
//        orderItemService.saveBatch(orderItemList);
//        //如使用优惠券更新优惠券使用状态
//        if (orderParam.getCouponId() != null && orderParam.getCouponId() > 0) {
//            couponHistory.setId(orderParam.getMemberCouponId());
//            couponHistory.setUseStatus(1);
//            couponHistory.setUseTime(new Date());
//            couponHistory.setOrderId(order.getId());
//            couponHistory.setOrderSn(order.getOrderSn());
//            couponHistoryService.updateById(couponHistory);
//        }
//        // 订单操作记录
//        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
//        history.setOrderId(order.getId());
//        history.setCreateTime(new Date());
//        history.setOperateMan("shop");
//        history.setPreStatus(-1);
//        history.setOrderStatus(OrderStatus.INIT.getValue());
//        history.setNote("创建订单");
//        orderOperateHistoryService.save(history);
//        stopWatch.stop();
//
//
//        stopWatch.start("5.锁库存 删除购物车");
//        lockStockByOrder(orderItemList, type);
//        //删除购物车中的下单商品
//        List<Long> ids = new ArrayList<>();
//        for (OmsCartItem cartPromotionItem : cartPromotionItemList) {
//            ids.add(cartPromotionItem.getId());
//        }
//        cartItemService.delete(currentMember.getId(), ids);
//        Map<String, Object> result = new HashMap<>();
//        result.put("order", order);
//        result.put("orderItemList", orderItemList);
//        stopWatch.stop();
//        log.info(stopWatch.prettyPrint());
//        return new CommonResult().success("下单成功", result);
//    }

    @Override
    public Object quitGroup(Long id) {
        groupMemberMapper.deleteById(id);

        return new CommonResult().success("下单成功");
    }

    @Override
    public CommonResult acceptGroup(OrderParam orderParam) {
        if (orderParam.getGroupType() == 2) {

        }
        OmsOrder order = new OmsOrder();

        UmsMember currentMember = memberService.getNewCurrentMember();
        if (currentMember == null) {
            return new CommonResult().fail(100);
        }
        List<OmsCartItem> list = new ArrayList<>();
        if (ValidatorUtils.empty(orderParam.getTotal())) {
            orderParam.setTotal(1);
        }
        OmsCartItem cartItem = new OmsCartItem();
        PmsProduct pmsProduct = productService.getById(orderParam.getGoodsId());
        createCartObj(orderParam, list, cartItem, pmsProduct);
        List<OmsOrderItem> orderItemList = new ArrayList<>();
        //获取购物车及优惠信息
        String name = "";
        for (OmsCartItem cartPromotionItem : list) {
            PmsProduct goods = productService.getById(cartPromotionItem.getProductId());
            if (!ValidatorUtils.empty(cartPromotionItem.getProductSkuId()) && cartPromotionItem.getProductSkuId() > 0) {
                checkGoods(goods, false, cartPromotionItem.getQuantity());
                PmsSkuStock skuStock = skuStockMapper.selectById(cartPromotionItem.getProductSkuId());
                checkSkuGoods(skuStock, cartPromotionItem.getQuantity());
            } else {
                checkGoods(goods, true, cartPromotionItem.getQuantity());
            }
            //生成下单商品信息
            OmsOrderItem orderItem = createOrderItem(cartPromotionItem);
            orderItemList.add(orderItem);
        }
        //进行库存锁定
        lockStock(list);
        //根据商品合计、运费、活动优惠、优惠券、积分计算应付金额
        UmsMemberReceiveAddress address = addressService.getById(orderParam.getAddressId());
        createOrderObj(order, orderParam, currentMember, orderItemList, address);
        order.setMemberId(currentMember.getId());
        SmsGroup group = groupMapper.getByGoodsId(orderParam.getGoodsId());
        Date endTime = DateUtils.convertStringToDate(DateUtils.addHours(group.getEndTime(), group.getHours()), "yyyy-MM-dd HH:mm:ss");

        // TODO: 2018/9/3 bill_*,delivery_*
        //插入order表和order_item表
        orderService.save(order);
        Long nowT = System.currentTimeMillis();
        if (nowT > group.getStartTime().getTime() && nowT < endTime.getTime()) {
            SmsGroupMember groupMember = new SmsGroupMember();
            SmsGroupRecord groupRecord = new SmsGroupRecord();
            if (orderParam.getGroupType() == 1) { // 1 发起拼团 2 参与拼团
                groupRecord.setCreateTime(new Date());
                groupRecord.setGroupId(group.getId());
                groupRecord.setStatus("1");
                groupRecordMapper.insert(groupRecord);

                groupMember.setGoodsId(orderParam.getGoodsId());
                groupMember.setName(currentMember.getNickname());
                groupMember.setMemberId(currentMember.getId());
                groupMember.setPic(currentMember.getIcon());
                groupMember.setStatus(1);
                groupMember.setOrderId(order.getId() + "");
                groupMember.setCreateTime(new Date());
                groupMember.setGroupRecordId(groupRecord.getId());
                groupMemberMapper.insert(groupMember);
            } else {
                List<SmsGroupMember> list1 = groupMemberMapper.selectList(new QueryWrapper<SmsGroupMember>().eq("group_record_id", orderParam.getMgId()));
                if (list1 != null && list1.size() > group.getMaxPeople()) {
                    return new CommonResult().failed("此拼团已达最大人数");
                }
                for (SmsGroupMember smsGroupMember : list1) {
                    if (smsGroupMember.getMemberId().equals(currentMember.getId())) {
                        return new CommonResult().failed("你已经参加过此团");
                    }
                }
                groupMember.setGoodsId(orderParam.getGoodsId());
                groupMember.setName(currentMember.getNickname());
                groupMember.setMemberId(currentMember.getId());
                groupMember.setPic(currentMember.getIcon());
                groupMember.setStatus(1);
                groupMember.setOrderId(order.getId() + "");
                groupMember.setCreateTime(new Date());
                groupMember.setGroupRecordId(orderParam.getMgId());
                groupMemberMapper.insert(groupMember);
            }
            order.setGroupId(groupMember.getId());
            orderMapper.updateById(order);
        } else {
            return new CommonResult().failed("活动已经结束");
        }
        for (OmsOrderItem orderItem : orderItemList) {
            orderItem.setOrderId(order.getId());
            orderItem.setOrderSn(order.getOrderSn());
        }

        orderItemService.saveBatch(orderItemList);
        //如使用优惠券更新优惠券使用状态
        if (orderParam.getCouponId() != null) {
            updateCouponStatus(orderParam.getCouponId(), currentMember.getId(), 1);
        }
        //如使用积分需要扣除积分
        if (orderParam.getUseIntegration() != null) {
            order.setUseIntegration(orderParam.getUseIntegration());
            memberService.updateIntegration(currentMember.getId(), currentMember.getIntegration() - orderParam.getUseIntegration());
        }

        Map<String, Object> result = new HashMap<>();
        result.put("order", order);
        result.put("orderItemList", orderItemList);

        String platform = orderParam.getPlatform();
        if ("1".equals(platform)) {
            push(currentMember, order, orderParam.getPage(), orderParam.getFormId(), name);
        }
        return new CommonResult().success("下单成功", result);
    }

    private void createCartObj(OrderParam orderParam, List<OmsCartItem> list, OmsCartItem cartItem, PmsProduct pmsProduct) {
        if (ValidatorUtils.notEmpty(orderParam.getSkuId())) {
            PmsSkuStock pmsSkuStock = skuStockMapper.selectById(orderParam.getSkuId());
            checkGoods(pmsProduct, false, 1);
            checkSkuGoods(pmsSkuStock, 1);
            cartItem.setProductId(pmsSkuStock.getProductId());
            cartItem.setMemberId(memberService.getNewCurrentMember().getId());
            cartItem.setProductSkuId(pmsSkuStock.getId());
            cartItem.setChecked(1);
            cartItem.setPrice(pmsSkuStock.getPrice());
            cartItem.setProductSkuCode(pmsSkuStock.getSkuCode());
            cartItem.setQuantity(orderParam.getTotal());
            cartItem.setProductAttr(pmsSkuStock.getMeno());
            cartItem.setProductPic(pmsSkuStock.getPic());
            cartItem.setSp1(pmsSkuStock.getSp1());
            cartItem.setSp2(pmsSkuStock.getSp2());
            cartItem.setSp3(pmsSkuStock.getSp3());
            cartItem.setProductName(pmsSkuStock.getProductName());
            cartItem.setProductCategoryId(pmsProduct.getProductCategoryId());
            cartItem.setProductBrand(pmsProduct.getBrandName());
            cartItem.setCreateDate(new Date());

        } else {
            checkGoods(pmsProduct, true, orderParam.getTotal());
            cartItem.setProductId(orderParam.getGoodsId());
            cartItem.setMemberId(memberService.getNewCurrentMember().getId());
            cartItem.setChecked(1);
            if (ValidatorUtils.notEmpty(orderParam.getGroupId())) {
                SmsGroup group = groupMapper.selectById(orderParam.getGroupId());
                if (group != null) {
                    cartItem.setPrice(group.getGroupPrice());
                } else {
                    cartItem.setPrice(pmsProduct.getPrice());
                }
            } else {
                cartItem.setPrice(pmsProduct.getPrice());
            }
            cartItem.setProductName(pmsProduct.getName());
            cartItem.setQuantity(orderParam.getTotal());
            cartItem.setProductPic(pmsProduct.getPic());
            cartItem.setCreateDate(new Date());
            cartItem.setMemberId(memberService.getNewCurrentMember().getId());
            cartItem.setProductCategoryId(pmsProduct.getProductCategoryId());
            cartItem.setProductBrand(pmsProduct.getBrandName());

        }
        list.add(cartItem);
    }

    private OmsOrderItem createOrderItem(OmsCartItem cartPromotionItem) {
        OmsOrderItem orderItem = new OmsOrderItem();
        orderItem.setProductAttr(cartPromotionItem.getProductAttr());
        orderItem.setProductId(cartPromotionItem.getProductId());
        orderItem.setProductName(cartPromotionItem.getProductName());
        orderItem.setProductPic(cartPromotionItem.getProductPic());
        orderItem.setProductAttr(cartPromotionItem.getProductAttr());
        orderItem.setProductBrand(cartPromotionItem.getProductBrand());
        orderItem.setProductSn(cartPromotionItem.getProductSn());
        orderItem.setProductPrice(cartPromotionItem.getPrice());
        orderItem.setProductQuantity(cartPromotionItem.getQuantity());
        orderItem.setProductSkuId(cartPromotionItem.getProductSkuId());
        orderItem.setProductSkuCode(cartPromotionItem.getProductSkuCode());
        orderItem.setProductCategoryId(cartPromotionItem.getProductCategoryId());
           /* orderItem.setPromotionAmount(cartPromotionItem.getReduceAmount());
            orderItem.setPromotionName(cartPromotionItem.getPromotionMessage());
            orderItem.setGiftIntegration(cartPromotionItem.getIntegration());
            orderItem.setGiftGrowth(cartPromotionItem.getGrowth());*/
        return orderItem;
    }

    private OmsOrderItem createOrderItemV1(OmsCartItem cartPromotionItem) {
//        @TableId(value = "id", type = IdType.AUTO)
//        private Long id;
//        private Long orderId;
//        private String orderSn;
//        private Long productId;
//        private String productPic;
//        private String productName;
//        private String productBrand;
//        private String productSn;
//        private BigDecimal productPrice;
//        private Integer productQuantity;
//        private Long productSkuId;
//        private String productSkuCode;
//        private Long productCategoryId;
//        private String sp1;
//        private String sp2;
//        private String sp3;
//
//        private BigDecimal couponAmount;
//
//
//        /**
//         * 该商品经过优惠后的分解金额
//         */
//        @TableField("real_amount")
//        private BigDecimal realAmount;
//
//        private String productAttr;
//
//
//        private Integer status;
//
//
//        private Integer type;
//
//        @TableField("total_order_sn")
//        private
//        String totalOrderSn;    //	总的订单号
        OmsOrderItem orderItem = new OmsOrderItem();
        orderItem.setProductAttr(cartPromotionItem.getProductAttr());
        orderItem.setProductId(cartPromotionItem.getProductId());
        orderItem.setProductName(cartPromotionItem.getProductName());
        orderItem.setProductPic(cartPromotionItem.getProductPic());
        orderItem.setProductAttr(cartPromotionItem.getProductAttr());
        orderItem.setProductBrand(cartPromotionItem.getProductBrand());
        orderItem.setProductSn(cartPromotionItem.getProductSn());
        orderItem.setProductPrice(cartPromotionItem.getPrice());  // 商品单价
        orderItem.setProductQuantity(cartPromotionItem.getQuantity());
        orderItem.setProductSkuId(cartPromotionItem.getProductSkuId());
        orderItem.setProductSkuCode(cartPromotionItem.getProductSkuCode());
        orderItem.setProductCategoryId(cartPromotionItem.getProductCategoryId());
        orderItem.setType(1); // 普通商品
        //orderItem.setRealAmount(); // 最后的价格=销售价-优惠价格
//        orderItem.setTotalOrderSn(totalOrderSn);
           /* orderItem.setPromotionAmount(cartPromotionItem.getReduceAmount());
            orderItem.setPromotionName(cartPromotionItem.getPromotionMessage());
            orderItem.setGiftIntegration(cartPromotionItem.getIntegration());
            orderItem.setGiftGrowth(cartPromotionItem.getGrowth());*/
        return orderItem;
    }

    /**
     * 计算订单商品表里最后该商品的实际付款价格
     *
     * @param couponId
     * @return
     */
    private BigDecimal getOmsOrderItemRealAmount(List<OmsCartItem> cartPromotionItemList, OmsCartItem omsCartItemInfo, Long couponId) {
        SmsCoupon coupon = null;
        if (couponId != null) {
            coupon = couponService.getById(couponId);
        }
        // 计算优惠券
        SmsCoupon smsCoupon = couponService.getById(couponId);
        if (smsCoupon == null) {
            //throw new ApiMallPlusException("优惠券不存在");
            return BigDecimal.ZERO;
        }
        // 判断优惠券是否过期了
        if (!this.belongCalendar(new Date(), smsCoupon.getStartTime(), smsCoupon.getEndTime())) {
            //throw new ApiMallPlusException("优惠券过期了");
            return BigDecimal.ZERO;
        }
        // 总金额数
        BigDecimal totalAmount = BigDecimal.ZERO;
        // 使用类型：0->全场通用；1->指定分类；2->指定商品use_type    3->店铺专用
        if (smsCoupon.getUseType().equals(0)) {// 全场通用
            for (OmsCartItem cartPromotionItem : cartPromotionItemList) {
                totalAmount = totalAmount.add(cartPromotionItem.getPrice().multiply(new BigDecimal(cartPromotionItem.getQuantity())));
            }
            // 单个商品
//            BigDecimal promotionPrice = omsCartItemInfo.getPrice().multiply(new BigDecimal(omsCartItemInfo.getQuantity())).divide(totalAmount);
            return BigDecimal.ZERO;
        } else if (smsCoupon.getUseType().equals(1)) { // 指定分类
            List<OmsCartItem> newCartPromotionItemList = new ArrayList<>(); // 有优惠券
            for (OmsCartItem cartPromotionItem : cartPromotionItemList) {
                // 查询分类
                QueryWrapper<SmsCouponProductCategoryRelation> query = new QueryWrapper();
                query.select("id");
                query.eq("coupon_id", couponId);
                query.eq("product_category_id", cartPromotionItem.getProductId());
                SmsCouponProductCategoryRelation smsCouponProductCategoryRelation = smsCouponProductCategoryRelationMapper.selectOne(query);
                if (smsCouponProductCategoryRelation != null) {
                    newCartPromotionItemList.add(cartPromotionItem);
                }
            }
            for (OmsCartItem cartPromotionItem : newCartPromotionItemList) {
                totalAmount = totalAmount.add(cartPromotionItem.getPrice().multiply(new BigDecimal(cartPromotionItem.getQuantity())));
            }
            // 单个商品
            BigDecimal promotionPrice = omsCartItemInfo.getPrice().multiply(new BigDecimal(omsCartItemInfo.getQuantity())).divide(totalAmount);
            return promotionPrice;
        } else if (smsCoupon.getUseType().equals(2)) {  // 指定商品
            List<OmsCartItem> newCartPromotionItemList = new ArrayList<>(); // 有优惠券
            for (OmsCartItem cartPromotionItem : cartPromotionItemList) {
                // 查询商品
                QueryWrapper<SmsCouponProductRelation> query = new QueryWrapper();
                query.select("id");
                query.eq("coupon_id", couponId);
                query.eq("product_id", cartPromotionItem.getProductId());
                SmsCouponProductRelation smsCouponProductRelation = smsCouponProductRelationMapper.selectOne(query);
                if (smsCouponProductRelation != null) {
                    newCartPromotionItemList.add(cartPromotionItem);
                }
            }
            for (OmsCartItem cartPromotionItem : newCartPromotionItemList) {
                totalAmount = totalAmount.add(cartPromotionItem.getPrice().multiply(new BigDecimal(cartPromotionItem.getQuantity())));
            }
            // 单个商品
//            BigDecimal promotionPrice = omsCartItemInfo.getPrice().multiply(new BigDecimal(omsCartItemInfo.getQuantity())).divide(totalAmount);
            //return promotionPrice;
            return BigDecimal.ZERO;
        } else if (smsCoupon.getUseType().equals(3)) {// 指定店铺
            List<OmsCartItem> newCartPromotionItemList = new ArrayList<>(); // 有优惠券
            for (OmsCartItem cartPromotionItem : cartPromotionItemList) {
                // 查询商品
                QueryWrapper<SmsCouponStoreRelation> query = new QueryWrapper();
                query.select("id");
                query.eq("coupon_id", couponId);
                query.eq("store_id", cartPromotionItem.getStoreId());
                SmsCouponStoreRelation smsCouponStoreRelation = couponStoreRelationMapper.selectOne(query);
                if (smsCouponStoreRelation != null) {
                    newCartPromotionItemList.add(cartPromotionItem);
                }
            }
            for (OmsCartItem cartPromotionItem : newCartPromotionItemList) {
                totalAmount = totalAmount.add(cartPromotionItem.getPrice().multiply(new BigDecimal(cartPromotionItem.getQuantity())));
            }
            // 单个商品
//            BigDecimal promotionPrice = omsCartItemInfo.getPrice().multiply(new BigDecimal(omsCartItemInfo.getQuantity())).divide(totalAmount);
//            return promotionPrice;
            return BigDecimal.ZERO;
        }
        return BigDecimal.ZERO;
    }

    /**
     * 创建订单对象
     *
     * @param order           订单对象
     * @param orderParam      订单参数
     * @param currentMember   当前用户
     * @param orderItemList   购物车信息
     * @param address         地址
     * @param coupon          优惠券
     * @param newCartItemList 购物车信息
     * @return
     */
    private OmsOrder createOrderObjV1(OmsOrder order, GenerateOrderParam orderParam, UmsMember currentMember, List<OmsOrderItem> orderItemList,
                                      UmsMemberReceiveAddress address, SmsCoupon coupon, List<OmsCartItem> newCartItemList) {
        ////////////////////////////////封装订单数据/////////////////////////
        order.setIsComment(1);  //是否评论，1未评论，2已评论
        order.setTaxType(1);    //	是否开发票 1=不发票 2=个人发票 3=公司发票
        order.setDiscountAmount(new BigDecimal(0)); // 管理员后台调整订单使用的折扣金额
        order.setCreateTime(new Date());  // 提交时间
        order.setMemberUsername(currentMember.getUsername()); // 用户帐号
        order.setMemberId(currentMember.getId());  // 用户id
        order.setPayType(0);//支付方式：0->未支付；1->支付宝；2->微信
        order.setSourceType(orderParam.getSource());//订单来源：0->PC订单；5->app订单 2 h5 3微信小程序 4 支付宝小程序
        order.setStatus(0);//订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
        order.setOrderType(orderParam.getOrderType());//订单类型：0->正常订单；1->秒杀订单
        //收货人信息：姓名、电话、邮编、地址
        if (address != null) {
            order.setReceiverId(address.getId());
            order.setReceiverName(address.getName());
            order.setReceiverPhone(address.getPhoneNumber());
            order.setReceiverPostCode(address.getPostCode());
            order.setReceiverProvince(address.getProvince());
            order.setReceiverCity(address.getCity());
            order.setReceiverRegion(address.getRegion());
            order.setReceiverDetailAddress(address.getDetailAddress());
        }
        //0->未确认；1->已确认
        order.setConfirmStatus(0);
        order.setDeleteStatus(0);
        if (orderParam.getCouponId() == null || orderParam.getCouponId() == 0) {
            order.setCouponAmount(new BigDecimal(0));
        } else {
            order.setCouponId(orderParam.getCouponId());
            order.setCouponAmount(this.calculationCoupon(newCartItemList, orderParam.getCouponId(), currentMember.getId()));// 优惠券抵扣金额
//            order.setCouponAmount(coupon.getAmount());  // 优惠券抵扣金额
        }
        order.setTotalAmount(calcTotalAmount(orderItemList));  // 订单总金额
        order.setPayAmount(calcPayAmountV1(order)); // 应付金额（实际支付金额）=总金额+运费-优惠券优惠
        if (order.getPayAmount().compareTo(BigDecimal.ZERO) < 0) {
            order.setPayAmount(new BigDecimal("0.01"));
        }
        //生成订单号
        order.setOrderSn(generateOrderSn(order));
//        // 若是平台有订单金额满足XXX元免邮，提交订单时的运费为0.
//        OmsSettingShop omsSettingShop = omsSettingShopMapper.selectOne(null);
//        if (order.getTotalAmount().compareTo(omsSettingShop.getFreeBuyAmount()) >= 0) {
//            // 免邮
//            order.setFreightAmount(new BigDecimal(0));
//        }
        order.setFreightAmount(new BigDecimal(0));
        log.info("订单支付金额1111：" + order.getPayAmount());
        ////////////////////////////////封装订单数据/////////////////////////
        return order;
    }

    private OmsOrder createOrderObj(OmsOrder order, OrderParam orderParam, UmsMember currentMember, List<OmsOrderItem> orderItemList, UmsMemberReceiveAddress address) {
        order.setIsComment(1);
        order.setTaxType(1);
        order.setDiscountAmount(new BigDecimal(0));
        order.setTotalAmount(calcTotalAmount(orderItemList));

        if (ValidatorUtils.notEmpty(orderParam.getGroupId())) {
            order.setGroupId(orderParam.getGroupId());
        }
        if (orderParam.getUseIntegration() == null) {
            order.setIntegration(0);
            order.setIntegrationAmount(new BigDecimal(0));
        } else {
            order.setIntegration(orderParam.getUseIntegration());
            order.setIntegrationAmount(calcIntegrationAmount(orderItemList));
        }
        //转化为订单信息并插入数据库
        order.setCreateTime(new Date());
        order.setMemberUsername(currentMember.getUsername());
        order.setMemberId(currentMember.getId());
        //支付方式：0->未支付；1->支付宝；2->微信
        order.setPayType(orderParam.getPayType());
        //订单来源：0->PC订单；5->app订单 2 h5 3微信小程序 4 支付宝小程序
        order.setSourceType(orderParam.getSource());
        //订单状态：订单状态：1->待付款；2->待发货；3->已发货；4->已完成；5->售后订单 6->已关闭；
        order.setStatus(OrderStatus.INIT.getValue());
        //订单类型：0->正常订单；1->秒杀订单
        order.setOrderType(orderParam.getOrderType());
        //收货人信息：姓名、电话、邮编、地址
        if (address != null) {
            order.setReceiverId(address.getId());
            order.setReceiverName(address.getName());
            order.setReceiverPhone(address.getPhoneNumber());
            order.setReceiverPostCode(address.getPostCode());
            order.setReceiverProvince(address.getProvince());
            order.setReceiverCity(address.getCity());
            order.setReceiverRegion(address.getRegion());
            order.setReceiverDetailAddress(address.getDetailAddress());
        }
        //0->未确认；1->已确认
        order.setConfirmStatus(0);
        order.setDeleteStatus(0);
        order.setMemberId(memberService.getNewCurrentMember().getId());
        //生成订单号
        order.setOrderSn(generateOrderSn(order));
        return order;
    }

    @Override
    @Transactional
    public boolean closeOrder(OmsOrder order) {
        releaseStock(order);
        order.setStatus(4); // 关闭订单
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(order.getId());
        history.setCreateTime(new Date());
        history.setOperateMan("shop");
        history.setPreStatus(OrderStatus.INIT.getValue());
        history.setOrderStatus(OrderStatus.CLOSED.getValue());
        history.setNote("关闭订单");
        orderOperateHistoryService.save(history);
        return orderMapper.updateById(order) > 0;
    }

    @Override
    @Transactional
    public boolean deleteOrder(OmsOrder order) {
        order.setDeleteStatus(1);
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(order.getId());
        history.setCreateTime(new Date());
        history.setOperateMan("shop");
        history.setPreStatus(0);
        history.setOrderStatus(1);
        history.setNote("删除订单");
        orderOperateHistoryService.save(history);
        return orderMapper.updateById(order) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PageInfo<OrderListInfo> getOrderList(String keyWord, Long memberId, Integer status, Integer pageIndex, Integer pageSize) {
        int start = (pageIndex - 1) * pageSize;
        int len = pageSize;
        if (StringUtils.isNumeric(keyWord)) {
            // 订单号查询
            List<OrderListInfo> omsOrderList = omsOrderMapper.getOrderList(keyWord, memberId, start, len, status);
            List<OrderListInfo> recordList = new ArrayList<>();
            for (OrderListInfo orderListInfo : omsOrderList) {
                List<OrderListItemInfo> orderListItemInfos = omsOrderItemMapper.getOrderItemList(orderListInfo.getOrderId());
                orderListInfo.setOrderListItemInfos(orderListItemInfos);
                recordList.add(orderListInfo);
            }
            return new PageInfo<>(pageIndex, pageSize, recordList);
        } else if (!StringUtils.isEmpty(keyWord)) {
            List<OrderListInfo> recordList = new ArrayList<>();
            // 商品名称查询
            List<OrderListItemInfo> orderListItemInfos = omsOrderItemMapper.getSearchOrderItemList(keyWord, memberId, status, start, len);
            Map<Long, List<OrderListItemInfo>> map = orderListItemInfos.stream().collect(Collectors.groupingBy(OrderListItemInfo::getOrderId));
            if (map.size() > 1) {
                for (Map.Entry<Long, List<OrderListItemInfo>> entry : map.entrySet()) {
                    Long orderId = entry.getKey();
                    List<OrderListItemInfo> list = entry.getValue();
                    OrderListInfo orderListInfo = omsOrderMapper.getOrderListInfo(orderId);
                    orderListInfo.setOrderListItemInfos(list);
                    recordList.add(orderListInfo);
                }
            }
            return new PageInfo<>(pageIndex, pageSize, recordList);
        } else {
            // 状态
            List<OrderListInfo> omsOrderList = omsOrderMapper.getOrderList(keyWord, memberId, start, len, status);
            List<OrderListInfo> recordList = new ArrayList<>();
            for (OrderListInfo orderListInfo : omsOrderList) {
                List<OrderListItemInfo> orderListItemInfos = omsOrderItemMapper.getOrderItemList(orderListInfo.getOrderId());
                orderListInfo.setOrderListItemInfos(orderListItemInfos);
                
                recordList.add(orderListInfo);
            }
            return new PageInfo<>(pageIndex, pageSize, recordList);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderDetailResult getOrderDetailResult(Long id) {
        OmsOrder omsOrder = omsOrderMapper.selectById(id);
        if (omsOrder == null) {
            throw new ApiMallPlusException("订单不存在！");
        }
        OrderDetailResult orderDetailResult = new OrderDetailResult();
        List<OrderListItemInfo> orderItemList = omsOrderItemMapper.getOrderItemList(id);
        List<OrderListItemInfo> list = new ArrayList<>();
        if (omsOrder.getStatus().equals(3)) {
            // 查询售后期
            OmsOrderSetting omsOrderSetting = orderSettingMapper.selectOne(null);
            Integer finishOvertime = omsOrderSetting.getFinishOvertime(); // 天数
            // 收货时间
            Date receiveTime = omsOrder.getReceiveTime();
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(receiveTime);
            calendar.add(calendar.DATE, finishOvertime);//把日期往后增加一天.整数往后推,负数往前移动
            Date currentTime = calendar.getTime();   //这个时间就是日期往后推一天的结果
            // 已完成
            for (OrderListItemInfo orderListItemInfo : orderItemList) {
                if (orderListItemInfo.getAftersalesStatus().equals(0)) {  // 正常
                    //判断是否过了售后期
                    if (currentTime.getTime() < System.currentTimeMillis()) {
                        orderListItemInfo.setAftersalesStatus(-1); // 过了售后期
                    }
                }
                list.add(orderListItemInfo);
            }
            // 商品列表
            orderDetailResult.setOrderListItemInfos(list);
        } else {
            // 商品列表
            orderDetailResult.setOrderListItemInfos(orderItemList);
        }
//        if (omsOrder.getStatus().equals(0)) { // 待付款
//            OmsOrderSetting orderSetting = orderSettingMapper.selectOne(new QueryWrapper<>());
//            // 获取超时的时间 常订单超时时间(分)
//            Integer normalOrderOvertime = orderSetting.getNormalOrderOvertime();
//            if (omsOrder.getCreateTime().getTime() + normalOrderOvertime * 60 * 1000L > System.currentTimeMillis()) {
//                // 取消订单
//                CommonResult result = this.cancelTimeOutOrder();
//                if (result.getCode() == 200) {
//                    omsOrder.setStatus(4); // 已关闭
//                }
//            } else {
//                orderDetailResult.setOrderCloseTime(omsOrder.getCreateTime().getTime() + normalOrderOvertime * 60 * 1000L - System.currentTimeMillis());   // 剩余毫秒
//            }
//        }
        orderDetailResult.setBuyerMessage(omsOrder.getNote()); // 备注：买家留言
        orderDetailResult.setDeliveryCompany(omsOrder.getDeliveryCompany());
        orderDetailResult.setDeliverySn(omsOrder.getDeliverySn());
        orderDetailResult.setIsComment(omsOrder.getIsComment());
        orderDetailResult.setOrderNo(omsOrder.getOrderSn());
        orderDetailResult.setOrderStatus(omsOrder.getStatus());
        orderDetailResult.setPayAmount(omsOrder.getPayAmount());
        orderDetailResult.setTotalAmount(omsOrder.getTotalAmount());
        orderDetailResult.setPayTime(DateUtil.dateToStr(omsOrder.getPaymentTime(), "yyyy-MM-dd HH:mm:ss"));
        orderDetailResult.setPayType(omsOrder.getPayType());
        orderDetailResult.setSubmitTime(DateUtil.dateToStr(omsOrder.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
        // 物流信息
        orderDetailResult.setLastDeliveryInfo("卖家已发货");
        orderDetailResult.setLastDeliveryTime("2020-01-20 12:00:12");
        orderDetailResult.setUserName(omsOrder.getReceiverName());
        orderDetailResult.setPhone(omsOrder.getReceiverPhone());
        orderDetailResult.setAddress(omsOrder.getReceiverDetailAddress());
        orderDetailResult.setFreightAmount(omsOrder.getFreightAmount());
        orderDetailResult.setCouponAmount(omsOrder.getCouponAmount());
        orderDetailResult.setOrderCloseTime(1000000L);
        orderDetailResult.setOrderId(omsOrder.getId());
        return orderDetailResult;
    }

    @Override
    public OmsCartItem saveOmsCartItemInfo(Long skuId, Long goodsId, Integer total, Long memberId) {
        OmsCartItem cartItem = new OmsCartItem();
        PmsProduct pmsProduct = productService.getById(goodsId);
        PmsSkuStock pmsSkuStock = skuStockMapper.selectById(skuId);
        ////////////////////////添加到购物车中///////////////////////////////////////////////
        cartItem.setProductId(goodsId);
        cartItem.setMemberId(memberId);
        cartItem.setProductSkuId(pmsSkuStock.getId());
        cartItem.setChecked(1);
        cartItem.setPrice(pmsProduct.getPrice());
        cartItem.setProductName(pmsProduct.getName());
        cartItem.setQuantity(total);
        cartItem.setProductPic(pmsProduct.getPic());
        cartItem.setCreateDate(new Date());
        cartItem.setMemberId(memberId);
        cartItem.setProductCategoryId(pmsProduct.getProductCategoryId());
        cartItem.setProductBrand(pmsProduct.getBrandName());
        cartItem.setStoreId(pmsProduct.getStoreId());
        cartItem.setStoreName(pmsProduct.getStoreName());
        cartItemMapper.insert(cartItem);
        return cartItem;
    }

    @Override
    public void paySuccessOrder(String orderNo, Integer payType) {
        // 修改订单表为success

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object confimDelivery(Long id) {
        OmsOrder order = this.orderMapper.selectById(id);
        // 订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
        if (order.getStatus() != 2) {
            return new CommonResult().paramFailed("已发货订单才能确认收货");
        }
        OmsOrderOperateHistory history = updateOrderInfo(id, order, OrderStatus.TO_DELIVER);
        history.setOrderStatus(3);
        history.setNote("确认收货");
        orderOperateHistoryService.save(history);
        order.setReceiveTime(new Date()); // 收货时间
        order.setStatus(3);   // 已完成
        this.orderMapper.updateById(order);
        return new CommonResult().success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object applyRefund(Long id) {
        OmsOrder order = this.orderMapper.selectById(id);
        try {
            if (order.getStatus() > 9) {
                return new CommonResult().paramFailed("已支付的订单才能申请退款");
            }
            OmsOrderOperateHistory history = updateOrderInfo(id, order, OrderStatus.REFUNDING);
            history.setOrderStatus(OrderStatus.REFUNDING.getValue());
            history.setNote("申请退款");
            orderOperateHistoryService.save(history);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new CommonResult().success();
    }

    private OmsOrderOperateHistory updateOrderInfo(Long id, OmsOrder order, OrderStatus refunding) {
        String key = Rediskey.orderDetail + "orderid" + id;
        redisService.remove(key);
        order.setStatus(refunding.getValue());
        orderMapper.updateById(order);

        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(order.getId());
        history.setCreateTime(new Date());
        history.setOperateMan("shop");
        history.setPreStatus(order.getStatus());
        return history;
    }

    @Override
    public Object orderComment(Long orderId, String items) {
        UmsMember member = memberService.getNewCurrentMember();
        List<ProductConsultParam> itemss = null;
        try {
            itemss = JsonUtils.json2list(items, ProductConsultParam.class);
            for (ProductConsultParam param : itemss) {
                PmsProductConsult productConsult = new PmsProductConsult();
                if (member != null) {
                    productConsult.setPic(member.getIcon());
                    productConsult.setMemberName(member.getNickname());
                    productConsult.setMemberId(member.getId());
                } else {
                    return new CommonResult().failed("请先登录");
                }
                productConsult.setGoodsId(param.getGoodsId());
                productConsult.setOrderId(orderId);
                productConsult.setConsultContent(param.getTextarea());
                productConsult.setStars(param.getScore());
                productConsult.setEmail(Arrays.toString(param.getImages()));
                productConsult.setConsultAddtime(new Date());
                productConsult.setType(AllEnum.ConsultType.ORDER.code());
                if (ValidatorUtils.empty(param.getTextarea()) && ValidatorUtils.empty(param.getImages())) {

                } else {
                    pmsProductConsultService.save(productConsult);
                }

            }
            OmsOrder omsOrder = new OmsOrder();
            omsOrder.setId(orderId);
            omsOrder.setIsComment(2);
            omsOrder.setStatus(OrderStatus.TRADE_SUCCESS.getValue());
            if (orderService.updateById(omsOrder)) {
                OmsOrderOperateHistory history = new OmsOrderOperateHistory();
                history.setOrderId(omsOrder.getId());
                history.setCreateTime(new Date());
                history.setOperateMan("shop");
                history.setPreStatus(OrderStatus.TO_COMMENT.getValue());
                history.setOrderStatus(OrderStatus.TRADE_SUCCESS.getValue());
                history.setNote("订单评价");
                orderOperateHistoryService.save(history);
                return new CommonResult().success(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new CommonResult().failed();
    }

    @Transactional
    @Override
    public OmsOrder blancePay(PayParam payParam) {
        OmsOrder order = orderMapper.selectById(payParam.getOrderId());
        UmsMember userDO = memberService.getNewCurrentMember();
        if (order.getPayAmount().compareTo(userDO.getBlance()) > 0) {
            throw new ApiMallPlusException("余额不足！");
        }
        order.setStatus(OrderStatus.TO_DELIVER.getValue());
        order.setPayType(AllEnum.OrderPayType.balancePay.code());
        order.setPaymentTime(new Date());
        orderService.updateById(order);
        if (ValidatorUtils.notEmpty(order.getGroupId())) {
            SmsGroupMember member = new SmsGroupMember();
            member.setId(order.getGroupId());
            member.setStatus(2);
            groupMemberMapper.updateById(member);

            SmsGroupMember groupMember = groupMemberMapper.selectById(order.getGroupId());
            SmsGroupRecord groupRecord = groupRecordMapper.selectById(groupMember.getGroupRecordId());
            SmsGroup group = groupMapper.selectById(groupRecord.getGroupId());

            List<SmsGroupMember> groupMembers = groupMemberMapper.selectList(new QueryWrapper<SmsGroupMember>().eq("group_record_id", groupRecord.getId()).eq("status", 2));
            groupRecord.setList(groupMembers);
            if (groupMembers != null && groupMembers.size() == group.getMaxPeople()) {
                groupRecord.setStatus("2");
                groupRecordMapper.updateById(groupRecord);
            }

        }
        if (order.getPayAmount().compareTo(BigDecimal.ZERO) < 0) {
            order.setPayAmount(new BigDecimal("0.01"));
        }
        userDO.setBlance(userDO.getBlance().subtract(order.getPayAmount()));
        memberService.updateById(userDO);
        UmsMemberBlanceLog blog = new UmsMemberBlanceLog();
        blog.setMemberId(userDO.getId());
        blog.setCreateTime(new Date());
        blog.setNote("支付订单：" + order.getId());
        blog.setPrice(order.getPayAmount());
        blog.setType(1);
        memberBlanceLogService.save(blog);
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(order.getId());
        history.setCreateTime(new Date());
        history.setOperateMan("shop");
        history.setPreStatus(OrderStatus.INIT.getValue());
        history.setOrderStatus(OrderStatus.TO_DELIVER.getValue());
        history.setNote("余额支付");
        orderOperateHistoryService.save(history);
        memberService.addIntegration(userDO.getId(), order.getPayAmount().multiply(new BigDecimal("0.1")).intValue(), 1, "余额支付添加积分", AllEnum.ChangeSource.order.code(), userDO.getUsername());

        return order;
    }

    @Transactional
    @Override
    public OmsOrder blancePay(OmsOrder order) {
        UmsMember userDO = memberService.getNewCurrentMember();
        if (order.getPayAmount().compareTo(userDO.getBlance()) > 0) {
            throw new ApiMallPlusException("余额不足！");
        }
        order.setStatus(OrderStatus.TO_DELIVER.getValue());
        order.setPayType(AllEnum.OrderPayType.balancePay.code());
        order.setPaymentTime(new Date());
        orderService.updateById(order);
        if (ValidatorUtils.notEmpty(order.getGroupId())) {
            SmsGroupMember member = new SmsGroupMember();
            member.setId(order.getGroupId());
            member.setStatus(2);
            groupMemberMapper.updateById(member);
        }
        if (order.getPayAmount().compareTo(BigDecimal.ZERO) < 0) {
            order.setPayAmount(new BigDecimal("0.01"));
        }
        userDO.setBlance(userDO.getBlance().subtract(order.getPayAmount()));
        memberService.updateById(userDO);
        UmsMemberBlanceLog blog = new UmsMemberBlanceLog();
        blog.setMemberId(userDO.getId());
        blog.setCreateTime(new Date());
        blog.setNote("支付订单：" + order.getId());
        blog.setPrice(order.getPayAmount());
        blog.setType(1);
        memberBlanceLogService.save(blog);
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(order.getId());
        history.setCreateTime(new Date());
        history.setOperateMan("shop");
        history.setPreStatus(OrderStatus.INIT.getValue());
        history.setOrderStatus(OrderStatus.TO_DELIVER.getValue());
        history.setNote("余额支付");
        orderOperateHistoryService.save(history);
        memberService.addIntegration(userDO.getId(), order.getPayAmount().multiply(new BigDecimal("0.1")).intValue(), 1, "余额支付添加积分", AllEnum.ChangeSource.order.code(), userDO.getUsername());

        return order;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int cancleDelivery(OmsOrder order, String remark) {
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(order.getId());
        history.setCreateTime(new Date());
        history.setOperateMan("shop");
        history.setPreStatus(order.getStatus());
        history.setOrderStatus(OrderStatus.TO_DELIVER.getValue());
        history.setNote("取消发货");
        orderOperateHistoryService.save(history);

        String key = Rediskey.orderDetail + "orderid" + order.getId();
        redisService.remove(key);
        order.setStatus(OrderStatus.TO_DELIVER.getValue());
        return orderMapper.updateById(order);
    }

    @Override
    @Transactional
    public Object jifenPay(OrderParam orderParam) {
        UmsMember member = memberService.getById(memberService.getNewCurrentMember().getId());
        PmsGifts gifts = giftsService.getById(orderParam.getGoodsId());
        if (gifts.getPrice().intValue() > member.getIntegration()) {
            return new CommonResult().failed("积分不足！");
        } else {
            // 插入订单
            OmsOrderItem orderItem = new OmsOrderItem();
            orderItem.setProductId(orderParam.getGoodsId());
            orderItem.setProductName(gifts.getTitle());
            orderItem.setProductPic(gifts.getIcon());
            orderItem.setProductPrice(gifts.getPrice());
            orderItem.setProductQuantity(1);
            orderItem.setProductCategoryId(gifts.getCategoryId());
            List<OmsOrderItem> omsOrderItemList = new ArrayList<>();
            omsOrderItemList.add(orderItem);
            OmsOrder order = new OmsOrder();
            createOrderObj(order, orderParam, member, omsOrderItemList, null);
            order.setOrderType(AllEnum.OrderType.JIFEN.code());
            order.setStatus(OrderStatus.TO_DELIVER.getValue());
            order.setPayType(AllEnum.OrderPayType.jifenPay.code());
            orderService.save(order);
            orderItem.setOrderId(order.getId());
            orderItemService.save(orderItem);

            OmsOrderOperateHistory history = new OmsOrderOperateHistory();
            history.setOrderId(order.getId());
            history.setCreateTime(new Date());
            history.setOperateMan("shop");
            history.setPreStatus(OrderStatus.INIT.getValue());
            history.setOrderStatus(OrderStatus.TO_DELIVER.getValue());
            history.setNote("积分兑换");
            orderOperateHistoryService.save(history);

            //修改会员积分
            member.setIntegration(member.getIntegration() - gifts.getPrice().intValue());
            memberService.updateById(member);
            // 插入积分日志表
            UmsIntegrationChangeHistory historyChange = new UmsIntegrationChangeHistory(member.getId(), new Date(), AllEnum.ChangeType.Min.code(), gifts.getPrice().intValue()
                    , member.getUsername(), order.getId() + "", AllEnum.ChangeSource.order.code());
            integrationChangeHistoryMapper.insert(historyChange);
            // 删除订单缓存
            String key = Rediskey.orderDetail + "orderid" + order.getId();
            redisService.remove(key);

        }
        return new CommonResult().success("兑换成功");
    }

    @Override
    public CommonResult paySuccess(Long orderId) {
        //修改订单支付状态
        OmsOrder order = new OmsOrder();
        order.setId(orderId);
        order.setStatus(OrderStatus.TO_DELIVER.getValue());
        order.setPaymentTime(new Date());
        orderService.updateById(order);
        //恢复所有下单商品的锁定库存，扣减真实库存
        OmsOrderItem queryO = new OmsOrderItem();
        queryO.setOrderId(orderId);
        String key = Rediskey.orderDetail + "orderid" + orderId;
        redisService.remove(key);
        List<OmsOrderItem> list = orderItemService.list(new QueryWrapper<>(queryO));
        int count = orderMapper.updateSkuStock(list);
        return new CommonResult().success("支付成功", count);
    }

    /**
     * 推送消息
     */
    public void push(UmsMember umsMember, OmsOrder order, String page, String formId, String name) {
        return;
    }

    @Override
    public CommonResult cancelTimeOutOrder() {
        OmsOrderSetting orderSetting = orderSettingMapper.selectOne(new QueryWrapper<>());
        if (orderSetting != null) {
            //查询超时、未支付的订单及订单详情
            List<OmsOrderDetail> timeOutOrders = orderMapper.getTimeOutOrders(orderSetting.getNormalOrderOvertime());
            if (CollectionUtils.isEmpty(timeOutOrders)) {
                return new CommonResult().failed("暂无超时订单");
            }
            //修改订单状态为交易取消
            List<Long> ids = new ArrayList<>();
            for (OmsOrderDetail timeOutOrder : timeOutOrders) {
                ids.add(timeOutOrder.getId());
            }
            orderMapper.updateOrderStatus(ids, 4);
            for (OmsOrderDetail timeOutOrder : timeOutOrders) {
                //解除订单商品库存锁定 库存+
                OmsOrder omsOrder = new OmsOrder();
                omsOrder.setId(timeOutOrder.getId());
                releaseStock(omsOrder);
                //修改优惠券使用状态
                updateCouponStatus(timeOutOrder.getCouponId(), timeOutOrder.getMemberId(), 0);
            }
        }
        return new CommonResult().success(null);
    }

    @Override
    public void cancelOrder(Long orderId) {
        //查询为付款的取消订单
        OmsOrder cancelOrder = orderMapper.selectById(orderId);
        if (cancelOrder != null) {
            //修改订单状态为取消
            cancelOrder.setStatus(OrderStatus.CLOSED.getValue());
            orderMapper.updateById(cancelOrder);
            OmsOrderItem queryO = new OmsOrderItem();
            queryO.setOrderId(orderId);
            //  List<OmsOrderItem> list = orderItemService.list(new QueryWrapper<>(queryO));
            //解除订单商品库存锁定
            //  orderMapper.releaseSkuStockLock(list);
            releaseStock(cancelOrder);
            //修改优惠券使用状态
            updateCouponStatus(cancelOrder.getCouponId(), cancelOrder.getMemberId(), 0);
            //返还使用积分
            if (cancelOrder.getUseIntegration() != null) {
                UmsMember member = memberService.getById(cancelOrder.getMemberId());
                memberService.updateIntegration(cancelOrder.getMemberId(), member.getIntegration() + cancelOrder.getUseIntegration());
            }
            OmsOrderOperateHistory history = new OmsOrderOperateHistory();
            history.setOrderId(orderId);
            history.setCreateTime(new Date());
            history.setOperateMan("shop");
            history.setPreStatus(cancelOrder.getStatus());
            history.setOrderStatus(OrderStatus.CLOSED.getValue());
            history.setNote("取消订单");
            orderOperateHistoryService.save(history);
        }
    }

    /**
     * 推送消息
     */
    public void push(GroupAndOrderVo umsMember, OmsOrder order, String page, String formId) {
        return;
    }

    /**
     * 生成18位订单编号:8位日期+2位平台号码+2位支付方式+6位以上自增id
     */
    private String generateOrderSn(OmsOrder order) {

        StringBuilder sb = new StringBuilder();
        sb.append(System.currentTimeMillis());
        sb.append(String.format("%02d", order.getSourceType()));
        sb.append(String.format("%02d", order.getPayType()));
        sb.append(order.getMemberId());
        return sb.toString();
    }

    /**
     * 计算总金额
     */
    private BigDecimal calcTotalAmount(List<OmsOrderItem> orderItemList) {
        BigDecimal totalAmount = new BigDecimal("0");
        for (OmsOrderItem item : orderItemList) {
            totalAmount = totalAmount.add(item.getProductPrice().multiply(new BigDecimal(item.getProductQuantity())));
        }
        return totalAmount;
    }

    /**
     * 锁定下单商品的所有库存
     */
    public void lockStockByOrder(List<OmsOrderItem> cartPromotionItemList, String type) {
        log.info("lockStockByOrder");
        for (OmsOrderItem item : cartPromotionItemList) {
            log.info("商品类型：" + item.getType());
            log.info("商品信息：" + item);
            if (!item.getType().equals(AllEnum.OrderItemType.GOODS.code())) { // 商品
                if (type != null && "6".equals(type)) {
                    SmsFlashPromotionProductRelation relation = smsFlashPromotionProductRelationService.getById(item.getGiftIntegration());
                    if ((relation.getFlashPromotionCount() - item.getProductQuantity()) < 0) {
                        throw new ApiMallPlusException("SmsFlashPromotionProductRelation is stock out. goodsId=" + item.getProductId() + ", relation=" + relation.getId());
                    }
                    relation.setFlashPromotionCount(relation.getFlashPromotionCount() - item.getProductQuantity());
                    smsFlashPromotionProductRelationService.updateById(relation);
                }
                PmsProduct goods = productService.getById(item.getProductId());
                if (goods != null && goods.getId() != null) {
                    PmsProduct newGoods = new PmsProduct();
                    newGoods.setId(goods.getId());
                    redisService.remove(String.format(Rediskey.GOODSDETAIL, goods.getId() + ""));
                    if (!ValidatorUtils.empty(item.getProductSkuId()) && item.getProductSkuId() > 0) {
                        PmsSkuStock skuStock = skuStockMapper.selectById(item.getProductSkuId());
                        if ((skuStock.getStock() - item.getProductQuantity()) < 0) {
                            throw new ApiMallPlusException("goods is stock out. goodsId=" + item.getProductId() + ", skuId=" + item.getProductSkuId());
                        } else {
                            skuStock.setId(item.getProductSkuId());
                            skuStock.setStock(skuStock.getStock() - item.getProductQuantity());
                            skuStockMapper.updateById(skuStock);
                        }
                    } else {
                        if ((goods.getStock() - item.getProductQuantity()) < 0) {
                            throw new ApiMallPlusException("goods is stock out. goodsId=" + item.getProductId() + ", goodsId=" + item.getProductSkuId());
                        }
                    }
                    newGoods.setSale(goods.getSale() + item.getProductQuantity());
                    newGoods.setStock(goods.getStock() - item.getProductQuantity());
                    productService.updateById(newGoods);
                }
            } else {
                PmsGifts goods = pmsGiftsService.getById(item.getProductId());
                if (goods != null && goods.getId() != null) {
                    PmsGifts newGoods = new PmsGifts();
                    newGoods.setId(goods.getId());
                    if ((goods.getStock() - item.getProductQuantity()) < 0) {
                        throw new ApiMallPlusException("赠礼商品 goods is stock out. goodsId=" + item.getProductId() + ", goodsId=" + item.getProductSkuId());
                    }
                    newGoods.setStock(goods.getStock() - item.getProductQuantity());
                    pmsGiftsService.updateById(newGoods);
                }

            }

        }
    }

    /**
     * 锁定下单商品的所有库存
     */
    public void lockStock(List<OmsCartItem> cartPromotionItemList) {
        log.info("lockStock");
        for (OmsCartItem item : cartPromotionItemList) {
            PmsProduct goods = productService.getById(item.getProductId());
            if (goods != null && goods.getId() != null) {
                PmsProduct newGoods = new PmsProduct();
                newGoods.setId(goods.getId());
                if (true) {
                    redisService.remove(String.format(Rediskey.GOODSDETAIL, goods.getId() + ""));
                    if (!ValidatorUtils.empty(item.getProductSkuId()) && item.getProductSkuId() > 0) {
                        PmsSkuStock skuStock = skuStockMapper.selectById(item.getProductSkuId());
                        if ((skuStock.getStock() - item.getQuantity()) < 0) {
                            throw new ApiMallPlusException("goods is stock out. goodsId=" + item.getProductId() + ", skuId=" + item.getProductSkuId());
                        } else {
                            skuStock.setId(item.getProductSkuId());
                            skuStock.setStock(skuStock.getStock() - item.getQuantity());
                            skuStockMapper.updateById(skuStock);
                        }
                    } else {
                        if ((goods.getStock() - item.getQuantity()) < 0) {
                            throw new ApiMallPlusException("goods is stock out. goodsId=" + item.getProductId() + ", goodsId=" + item.getProductSkuId());
                        }
                    }
                }
                newGoods.setSale(goods.getSale() + item.getQuantity());
                newGoods.setStock(goods.getStock() - item.getQuantity());
                productService.updateById(newGoods);
            }
        }
    }

    /**
     * 解锁下单商品的所有库存
     */
    @Override
    public void releaseStock(OmsOrder order) {
        List<OmsOrderItem> orderItemList = orderItemService.list(new QueryWrapper<OmsOrderItem>().eq("order_id", order.getId()));
        log.info("releaseStock");
        for (OmsOrderItem item : orderItemList) {
            if (item.getType().equals(AllEnum.OrderItemType.GOODS.code())) {
//                if ("6".equals(order.getOrderType())) {
//                    SmsFlashPromotionProductRelation relation = smsFlashPromotionProductRelationService.getById(item.getGiftIntegration().longValue());
//                    relation.setFlashPromotionCount(relation.getFlashPromotionCount() + item.getProductQuantity());
//                    smsFlashPromotionProductRelationService.updateById(relation);
//                }
                PmsProduct goods = productService.getById(item.getProductId());
                if (goods != null && goods.getId() != null) {
                    PmsProduct newGoods = new PmsProduct();
                    newGoods.setId(goods.getId());
                    if (true) {
                        redisService.remove(String.format(Rediskey.GOODSDETAIL, goods.getId() + ""));
                        if (!ValidatorUtils.empty(item.getProductSkuId()) && item.getProductSkuId() > 0) {
                            PmsSkuStock skuStock = skuStockMapper.selectById(item.getProductSkuId());
                            skuStock.setId(item.getProductSkuId());
                            skuStock.setStock(skuStock.getStock() + item.getProductQuantity());
                            skuStockMapper.updateById(skuStock);
                        }
                    }
                    goods.setSale(goods.getSale() - item.getProductQuantity());
                    newGoods.setStock(goods.getStock() + item.getProductQuantity());
                    productService.updateById(newGoods);
                }
            }
//            else {
////                PmsGifts goods = pmsGiftsService.getById(item.getProductId());
////                if (goods != null && goods.getId() != null) {
////                    PmsGifts newGoods = new PmsGifts();
////                    newGoods.setId(goods.getId());
////                    if ((goods.getStock() + item.getProductQuantity()) < 0) {
////                        throw new ApiMallPlusException("goods is stock out. goodsId=" + item.getProductId() + ", goodsId=" + item.getProductSkuId());
////                    }
////                    newGoods.setStock(goods.getStock() + item.getProductQuantity());
////                    pmsGiftsService.updateById(newGoods);
////                }
//            }
        }
    }

    /**
     * 判断下单商品是否都有库存
     */
    private boolean hasStock(List<OmsCartItem> cartPromotionItemList) {

        return true;
    }

    /**
     * 计算购物车中商品的价格
     */
    private ConfirmOrderResult.CalcAmount calcCartAmount(List<OmsCartItem> cartPromotionItemList, BigDecimal transFee, BigDecimal payAmount) {
        ConfirmOrderResult.CalcAmount calcAmount = new ConfirmOrderResult.CalcAmount();
        calcAmount.setFreightAmount(transFee);


        BigDecimal totalAmount = new BigDecimal("0");
        BigDecimal promotionAmount = new BigDecimal("0");
        CartMarkingVo vo = new CartMarkingVo();
        vo.setCartList(cartPromotionItemList);
        SmsBasicMarking basicMarking = basicMarkingService.matchOrderBasicMarking(vo);
        log.info("basicMarking=" + com.alibaba.fastjson.JSONObject.toJSONString(basicMarking));
        if (basicMarking != null) {
            promotionAmount = basicMarking.getMinAmount();
        }
        if (promotionAmount == null) {
            promotionAmount = BigDecimal.ZERO;
        }
        for (OmsCartItem cartPromotionItem : cartPromotionItemList) {
            totalAmount = totalAmount.add(cartPromotionItem.getPrice().multiply(new BigDecimal(cartPromotionItem.getQuantity())));
            //  promotionAmount = promotionAmount.add(cartPromotionItem.getReduceAmount().multiply(new BigDecimal(cartPromotionItem.getQuantity())));
        }
        calcAmount.setTotalAmount(totalAmount);
        calcAmount.setPromotionAmount(promotionAmount);
        if (payAmount.compareTo(BigDecimal.ZERO) > 0) {
            calcAmount.setPayAmount(payAmount.subtract(promotionAmount).add(transFee));
        } else {
            calcAmount.setPayAmount(totalAmount.subtract(promotionAmount).add(transFee));
        }
        if (calcAmount.getPayAmount().compareTo(BigDecimal.ZERO) < 0) {
            calcAmount.setPayAmount(new BigDecimal("0.01"));
        }
        return calcAmount;
    }

    /**
     * 计算购物车中商品的各个价格
     */
    private ConfirmOrderResult.CalcAmount calcCartAllAmount(List<OmsCartItem> cartPromotionItemList, BigDecimal payAmount, Long couponId, Long memberId) {
        // 计算运费
        BigDecimal transFee = this.getOrderTransFee(cartPromotionItemList);
        ConfirmOrderResult.CalcAmount calcAmount = new ConfirmOrderResult.CalcAmount();
        calcAmount.setFreightAmount(transFee);
        //  计算优惠金额
        BigDecimal promotionAmount = this.calculationCoupon(cartPromotionItemList, couponId, memberId);
        if (promotionAmount == null) {
            promotionAmount = BigDecimal.ZERO;
        }
        // 计算总的金额
        BigDecimal totalAmount = new BigDecimal("0");
        for (OmsCartItem cartPromotionItem : cartPromotionItemList) {
            totalAmount = totalAmount.add(cartPromotionItem.getPrice().multiply(new BigDecimal(cartPromotionItem.getQuantity())));
        }
        calcAmount.setTotalAmount(totalAmount);
        calcAmount.setPromotionAmount(promotionAmount);
        // 计算应付金额
        if (payAmount.compareTo(BigDecimal.ZERO) > 0) {
            calcAmount.setPayAmount(payAmount.subtract(promotionAmount).add(transFee));
        } else {
            calcAmount.setPayAmount(totalAmount.subtract(promotionAmount).add(transFee));
        }
        if (calcAmount.getPayAmount().compareTo(BigDecimal.ZERO) < 0) {
            calcAmount.setPayAmount(new BigDecimal("0.01"));
        }
        return calcAmount;
    }

    /**
     * 删除下单商品的购物车信息
     */
    private void deleteCartItemList(List<OmsCartItem> cartPromotionItemList, UmsMember currentMember) {
        List<Long> ids = new ArrayList<>();
        for (OmsCartItem cartPromotionItem : cartPromotionItemList) {
            ids.add(cartPromotionItem.getId());
        }
        cartItemService.delete(currentMember.getId(), ids);
    }

    /**
     * 将优惠券信息更改为指定状态
     *
     * @param couponId  优惠券id
     * @param memberId  会员id
     * @param useStatus 0->未使用；1->已使用
     */
    private void updateCouponStatus(Long couponId, Long memberId, Integer useStatus) {
        if (couponId == null) {
            return;
        }
        //查询第一张优惠券
        SmsCouponHistory queryC = new SmsCouponHistory();
        queryC.setCouponId(couponId);
        if (useStatus == 0) {
            queryC.setUseStatus(1);
        } else {
            queryC.setUseStatus(0);
        }
        List<SmsCouponHistory> couponHistoryList = couponHistoryService.list(new QueryWrapper<>(queryC));
        if (!CollectionUtils.isEmpty(couponHistoryList)) {
            SmsCouponHistory couponHistory = couponHistoryList.get(0);
            couponHistory.setUseTime(new Date());
            couponHistory.setUseStatus(useStatus);
            couponHistoryService.updateById(couponHistory);
        }
    }

    /**
     * 获取订单促销信息
     */
    private String getOrderPromotionInfo(List<OmsOrderItem> orderItemList) {
        StringBuilder sb = new StringBuilder();
        for (OmsOrderItem orderItem : orderItemList) {
            sb.append(orderItem.getPromotionName());
            sb.append(",");
        }
        String result = sb.toString();
        if (result.endsWith(",")) {
            result = result.substring(0, result.length() - 1);
        }
        return result;
    }

    /**
     * 计算订单应付金额=总金额+运费-促销优惠-优惠券优惠-积分抵扣
     */
    private BigDecimal calcPayAmount(OmsOrder order) {
        if (order.getPromotionAmount() == null) {
            order.setPromotionAmount(BigDecimal.ZERO);
        }
        if (order.getFreightAmount() == null) {
            order.setFreightAmount(BigDecimal.ZERO);
        }
        //总金额+运费-促销优惠-优惠券优惠-积分抵扣
        BigDecimal payAmount = order.getTotalAmount()
                .add(order.getFreightAmount())
                .subtract(order.getPromotionAmount())
                .subtract(order.getCouponAmount());
        return payAmount;
    }

    /**
     * 计算订单应付金额=总金额+运费-优惠券优惠
     */
    private BigDecimal calcPayAmountV1(OmsOrder order) {
        if (order.getFreightAmount() == null) {
            order.setFreightAmount(BigDecimal.ZERO);
        }
        //总金额+运费-优惠券优惠
        BigDecimal payAmount = order.getTotalAmount()
                .add(order.getFreightAmount())
                .subtract(order.getCouponAmount());
        log.info("计算订单应付金额");
        log.info("TotalAmount" + order.getTotalAmount());
        log.info("FreightAmount" + order.getFreightAmount());
        log.info("CouponAmount" + order.getCouponAmount());
        return payAmount;
    }

    /**
     * 计算订单优惠券金额
     */
    private BigDecimal calcIntegrationAmount(List<OmsOrderItem> orderItemList) {
        BigDecimal integrationAmount = new BigDecimal(0);
        for (OmsOrderItem orderItem : orderItemList) {
            if (orderItem.getIntegrationAmount() != null) {
                integrationAmount = integrationAmount.add(orderItem.getIntegrationAmount().multiply(new BigDecimal(orderItem.getProductQuantity())));
            }
        }
        return integrationAmount;
    }

    /**
     * 计算订单优惠券金额
     */
    private BigDecimal calcCouponAmount(List<OmsOrderItem> orderItemList) {
        BigDecimal couponAmount = new BigDecimal(0);
        for (OmsOrderItem orderItem : orderItemList) {
            if (orderItem.getCouponAmount() != null) {
                couponAmount = couponAmount.add(orderItem.getCouponAmount().multiply(new BigDecimal(orderItem.getProductQuantity())));
            }
        }
        return couponAmount;
    }

    /**
     * 计算订单活动优惠
     */
    private BigDecimal calcPromotionAmount(List<OmsOrderItem> orderItemList) {
        BigDecimal promotionAmount = new BigDecimal(0);
        for (OmsOrderItem orderItem : orderItemList) {
            if (orderItem.getPromotionAmount() != null) {
                promotionAmount = promotionAmount.add(orderItem.getPromotionAmount().multiply(new BigDecimal(orderItem.getProductQuantity())));
            }
        }
        return promotionAmount;
    }

    /**
     * 获取可用积分抵扣金额
     *
     * @param useIntegration 使用的积分数量
     * @param totalAmount    订单总金额
     * @param currentMember  使用的用户
     * @param hasCoupon      是否已经使用优惠券
     */
    private BigDecimal getUseIntegrationAmount(Integer useIntegration, BigDecimal totalAmount, UmsMember currentMember, boolean hasCoupon) {
        BigDecimal zeroAmount = new BigDecimal(0);
        //判断用户是否有这么多积分
        if (useIntegration.compareTo(currentMember.getIntegration()) > 0) {
            return zeroAmount;
        }
        //根据积分使用规则判断使用可用
        //是否可用于优惠券共用
        UmsIntegrationConsumeSetting integrationConsumeSetting = integrationConsumeSettingMapper.selectById(1L);
        if (hasCoupon && integrationConsumeSetting.getCouponStatus().equals(0)) {
            //不可与优惠券共用
            return zeroAmount;
        }
        //是否达到最低使用积分门槛
        if (useIntegration.compareTo(integrationConsumeSetting.getUseUnit()) < 0) {
            return zeroAmount;
        }
        //是否超过订单抵用最高百分比
        BigDecimal integrationAmount = new BigDecimal(useIntegration).divide(new BigDecimal(integrationConsumeSetting.getUseUnit()), 2, RoundingMode.HALF_EVEN);
        BigDecimal maxPercent = new BigDecimal(integrationConsumeSetting.getMaxPercentPerOrder()).divide(new BigDecimal(100), 2, RoundingMode.HALF_EVEN);
        if (integrationAmount.compareTo(totalAmount.multiply(maxPercent)) > 0) {
            return zeroAmount;
        }
        return integrationAmount;
    }

    /**
     * 对优惠券优惠进行处理
     *
     * @param orderItemList       order_item列表
     * @param couponHistoryDetail 可用优惠券详情
     */
    private void handleCouponAmount(List<OmsOrderItem> orderItemList, SmsCouponHistoryDetail couponHistoryDetail) {
        SmsCoupon coupon = couponHistoryDetail.getCoupon();
        if (coupon.getUseType().equals(0)) {
            //全场通用
            calcPerCouponAmount(orderItemList, coupon);
        } else if (coupon.getUseType().equals(1)) {
            //指定分类
            List<OmsOrderItem> couponOrderItemList = getCouponOrderItemByRelation(couponHistoryDetail, orderItemList, 0);
            calcPerCouponAmount(couponOrderItemList, coupon);
        } else if (coupon.getUseType().equals(2)) {
            //指定商品
            List<OmsOrderItem> couponOrderItemList = getCouponOrderItemByRelation(couponHistoryDetail, orderItemList, 1);
            calcPerCouponAmount(couponOrderItemList, coupon);
        }
    }

    /**
     * 对每个下单商品进行优惠券金额分摊的计算
     *
     * @param orderItemList 可用优惠券的下单商品商品
     */
    private void calcPerCouponAmount(List<OmsOrderItem> orderItemList, SmsCoupon coupon) {
        BigDecimal totalAmount = calcTotalAmount(orderItemList);
        for (OmsOrderItem orderItem : orderItemList) {
            //(商品价格/可用商品总价)*优惠券面额
            BigDecimal couponAmount = orderItem.getProductPrice().divide(totalAmount, 3, RoundingMode.HALF_EVEN).multiply(coupon.getAmount());
            orderItem.setCouponAmount(couponAmount);
        }
    }

    /**
     * 获取与优惠券有关系的下单商品
     *
     * @param couponHistoryDetail 优惠券详情
     * @param orderItemList       下单商品
     * @param type                使用关系类型：0->相关分类；1->指定商品
     */
    private List<OmsOrderItem> getCouponOrderItemByRelation(SmsCouponHistoryDetail couponHistoryDetail, List<OmsOrderItem> orderItemList, int type) {
        List<OmsOrderItem> result = new ArrayList<>();
        if (type == 0) {
            List<Long> categoryIdList = new ArrayList<>();
            for (SmsCouponProductCategoryRelation productCategoryRelation : couponHistoryDetail.getCategoryRelationList()) {
                categoryIdList.add(productCategoryRelation.getProductCategoryId());
            }
            for (OmsOrderItem orderItem : orderItemList) {
                if (categoryIdList.contains(orderItem.getProductCategoryId())) {
                    result.add(orderItem);
                } else {
                    orderItem.setCouponAmount(new BigDecimal(0));
                }
            }
        } else if (type == 1) {
            List<Long> productIdList = new ArrayList<>();
            for (SmsCouponProductRelation productRelation : couponHistoryDetail.getProductRelationList()) {
                productIdList.add(productRelation.getProductId());
            }
            for (OmsOrderItem orderItem : orderItemList) {
                if (productIdList.contains(orderItem.getProductId())) {
                    result.add(orderItem);
                } else {
                    orderItem.setCouponAmount(new BigDecimal(0));
                }
            }
        }
        return result;
    }

    @Override
    public Object addGroup(OrderParam orderParam) {
        List<OmsCartItem> list = new ArrayList<>();
        if (ValidatorUtils.empty(orderParam.getTotal())) {
            orderParam.setTotal(1);
        }
        OmsCartItem cartItem = new OmsCartItem();
        PmsProduct pmsProduct = productService.getById(orderParam.getGoodsId());
        createCartObj(orderParam, list, cartItem, pmsProduct);
        ConfirmOrderResult result = new ConfirmOrderResult();
        //获取购物车信息
        List<OmsCartItem> newCartList = new ArrayList<>();
        // 取商品大的运费
        BigDecimal transFee = BigDecimal.ZERO;
        for (OmsCartItem cart : list) {
            PmsProduct goods = productService.getById(cart.getProductId());
            if (goods != null && goods.getStock() > 0 && goods.getStock() >= cart.getQuantity()) {
                if (goods.getTransfee().compareTo(transFee) > 0) {
                    transFee = goods.getTransfee();
                }
            }

            newCartList.add(cart);
        }
        result.setCartPromotionItemList(newCartList);
        //获取用户收货地址列表
        UmsMemberReceiveAddress queryU = new UmsMemberReceiveAddress();
        if (memberService.getNewCurrentMember() == null) {
            return new CommonResult().fail(100);
        }
        queryU.setMemberId(memberService.getNewCurrentMember().getId());
        List<UmsMemberReceiveAddress> memberReceiveAddressList = addressService.list(new QueryWrapper<>(queryU));
        result.setMemberReceiveAddressList(memberReceiveAddressList);
        UmsMemberReceiveAddress address = addressService.getDefaultItem();
        //获取用户可用优惠券列表
        List<SmsCouponHistoryDetail> couponHistoryDetailList = couponService.listCart(newCartList, 1);
        result.setCouponHistoryDetailList(couponHistoryDetailList);
        UmsMember member = memberService.getById(memberService.getNewCurrentMember().getId());
        if (member == null) {
            return new CommonResult().fail(100);
        }

        //获取用户积分
        result.setMemberIntegration(member.getIntegration());
        //获取积分使用规则
        UmsIntegrationConsumeSetting integrationConsumeSetting = integrationConsumeSettingMapper.selectById(1L);
        result.setIntegrationConsumeSetting(integrationConsumeSetting);
        //计算总金额、活动优惠、应付金额
        ConfirmOrderResult.CalcAmount calcAmount = calcCartAmount(newCartList, transFee, BigDecimal.ZERO);
        result.setCalcAmount(calcAmount);
        result.setAddress(address);
        return result;
    }

    @Override
    public Object addCart(CartParam cartParam) {
        Integer stock = 0;

        // 校验用户
        if (ValidatorUtils.empty(memberService.getNewCurrentMember().getId())) {
            return new CommonResult().fail(100);
        }
        // 校验数量
        if (ValidatorUtils.empty(cartParam.getTotal())) {
            cartParam.setTotal(1);
        }
        OmsCartItem cartItem = new OmsCartItem();
        PmsProduct pmsProduct = productService.getById(cartParam.getGoodsId());
        // 库存id
        if (ValidatorUtils.notEmpty(cartParam.getSkuId())) {
            PmsSkuStock pmsSkuStock = skuStockMapper.selectById(cartParam.getSkuId());

            stock = pmsSkuStock.getStock();


            checkGoods(pmsProduct, false, cartParam.getTotal());
            checkSkuGoods(pmsSkuStock, cartParam.getTotal());
            cartItem.setProductId(pmsSkuStock.getProductId());
            cartItem.setMemberId(memberService.getNewCurrentMember().getId());
            cartItem.setProductSkuId(pmsSkuStock.getId());
            // 检查购物的商品是否存在
            OmsCartItem existCartItem = cartItemMapper.selectOne(new QueryWrapper<>(cartItem));
            if (existCartItem == null) {
                // 不存在，插入
                cartItem.setChecked(1);
                cartItem.setMemberId(memberService.getNewCurrentMember().getId());
                cartItem.setPrice(pmsSkuStock.getPrice());
                cartItem.setProductSkuCode(pmsSkuStock.getSkuCode());
                cartItem.setQuantity(cartParam.getTotal());
                cartItem.setProductAttr(pmsSkuStock.getMeno());
                cartItem.setProductPic(pmsSkuStock.getPic());
                cartItem.setPresentPrice(pmsSkuStock.getPrice());
                cartItem.setSp1(pmsSkuStock.getSp1());
                cartItem.setSp2(pmsSkuStock.getSp2());
                cartItem.setSp3(pmsSkuStock.getSp3());
                cartItem.setProductName(pmsSkuStock.getProductName());
                cartItem.setProductCategoryId(pmsProduct.getProductCategoryId());
                cartItem.setProductBrand(pmsProduct.getBrandName());
                cartItem.setCreateDate(new Date());
                cartItem.setStoreId(pmsProduct.getStoreId());
                cartItem.setStoreName(pmsProduct.getStoreName());
                cartItemMapper.insert(cartItem);
            } else {
                // 存在，更新

                if (existCartItem.getQuantity() + cartParam.getTotal() > stock) {
                    return new CommonResult().failed(203, "库存不足");
                }


                existCartItem.setPrice(pmsSkuStock.getPrice());
                existCartItem.setModifyDate(new Date());
                existCartItem.setQuantity(existCartItem.getQuantity() + cartParam.getTotal());
                cartItemMapper.updateById(existCartItem);
                return new CommonResult().success(existCartItem);
            }
        } else {
            checkGoods(pmsProduct, true, cartParam.getTotal());
            cartItem.setProductId(cartParam.getGoodsId());
            cartItem.setMemberId(memberService.getNewCurrentMember().getId());
            OmsCartItem existCartItem = cartItemMapper.selectOne(new QueryWrapper<>(cartItem));
            if (existCartItem == null) {
                cartItem.setChecked(1);
                cartItem.setPrice(pmsProduct.getPrice());
                cartItem.setPresentPrice(pmsProduct.getPrice());
                cartItem.setProductName(pmsProduct.getName());
                cartItem.setQuantity(cartParam.getTotal());
                cartItem.setProductPic(pmsProduct.getPic());
                cartItem.setCreateDate(new Date());
                cartItem.setMemberId(memberService.getNewCurrentMember().getId());
                cartItem.setProductCategoryId(pmsProduct.getProductCategoryId());
                cartItem.setProductBrand(pmsProduct.getBrandName());
                cartItem.setStoreId(pmsProduct.getStoreId());
                cartItem.setStoreName(pmsProduct.getStoreName());
                cartItemMapper.insert(cartItem);
            } else {

                if (existCartItem.getQuantity() + cartParam.getTotal() > stock) {
                    return new CommonResult().failed(203, "库存不足");
                }

                existCartItem.setPrice(pmsProduct.getPrice());
                existCartItem.setModifyDate(new Date());
                existCartItem.setQuantity(existCartItem.getQuantity() + cartParam.getTotal());
                cartItemMapper.updateById(existCartItem);
                return new CommonResult().success(existCartItem);
            }
        }
        return new CommonResult().success(cartItem);
    }

    /**
     * 立即购买/快速下单
     *
     * @param cartParam
     * @return
     */
    @Override
    public Object doGoBuy(CartParam cartParam) {
        return null;
    }

    /**
     * 计算优惠券金额：核心业务逻辑
     *
     * @param cartPromotionItemList 购物车商品
     * @param couponId              优惠券id
     * @param memberId              用户id
     * @return
     */
    @Override
    public BigDecimal calculationCoupon(List<OmsCartItem> cartPromotionItemList, Long couponId, Long memberId) {
        // 计算优惠券
        SmsCoupon smsCoupon = couponService.getById(couponId);
        if (smsCoupon == null) {
            //throw new ApiMallPlusException("优惠券不存在");
            return BigDecimal.ZERO;
        }
        // 判断优惠券是否过期了
        if (!this.belongCalendar(new Date(), smsCoupon.getStartTime(), smsCoupon.getEndTime())) {
            //throw new ApiMallPlusException("优惠券过期了");
            return BigDecimal.ZERO;
        }
        // 总金额数
        BigDecimal totalAmount = BigDecimal.ZERO;
        BigDecimal totalPromotionPrice = BigDecimal.ZERO;
        // 使用类型：0->全场通用；1->指定分类；2->指定商品use_type    3->店铺专用
        if (smsCoupon.getUseType().equals(0)) {// 全场通用
            for (OmsCartItem cartPromotionItem : cartPromotionItemList) {
                totalAmount = totalAmount.add(cartPromotionItem.getPrice().multiply(new BigDecimal(cartPromotionItem.getQuantity())));
            }
            log.info("全场通用totalAmount：" + totalAmount);
            for (OmsCartItem omsCartItem : cartPromotionItemList) {
                log.info("Price：" + omsCartItem.getPrice());
                log.info("Quantity：" + omsCartItem.getQuantity());
                try {
                    BigDecimal promotionPrice = (omsCartItem.getPrice().multiply(new BigDecimal(omsCartItem.getQuantity()))).divide(totalAmount, 2, BigDecimal.ROUND_DOWN);
                    totalPromotionPrice = promotionPrice.add(totalPromotionPrice);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
            return totalPromotionPrice;
        } else if (smsCoupon.getUseType().equals(1)) { // 指定分类
            List<OmsCartItem> newCartPromotionItemList = new ArrayList<>(); // 有优惠券
            for (OmsCartItem cartPromotionItem : cartPromotionItemList) {
                // 查询分类
                QueryWrapper<SmsCouponProductCategoryRelation> query = new QueryWrapper();
                query.select("id");
                query.eq("coupon_id", couponId);
                query.eq("product_category_id", cartPromotionItem.getProductId());
                SmsCouponProductCategoryRelation smsCouponProductCategoryRelation = smsCouponProductCategoryRelationMapper.selectOne(query);
                if (smsCouponProductCategoryRelation != null) {
                    newCartPromotionItemList.add(cartPromotionItem);
                }
            }
            for (OmsCartItem cartPromotionItem : newCartPromotionItemList) {
                totalAmount = totalAmount.add(cartPromotionItem.getPrice().multiply(new BigDecimal(cartPromotionItem.getQuantity())));
            }
            for (OmsCartItem omsCartItem : newCartPromotionItemList) {
                BigDecimal promotionPrice = omsCartItem.getPrice().multiply(new BigDecimal(omsCartItem.getQuantity())).divide(totalAmount, 2, BigDecimal.ROUND_DOWN);
                totalPromotionPrice = promotionPrice.add(totalPromotionPrice);
            }
            return totalPromotionPrice;
        } else if (smsCoupon.getUseType().equals(2)) {  // 指定商品
            List<OmsCartItem> newCartPromotionItemList = new ArrayList<>(); // 有优惠券
            for (OmsCartItem cartPromotionItem : cartPromotionItemList) {
                // 查询商品
                QueryWrapper<SmsCouponProductRelation> query = new QueryWrapper();
                query.select("id");
                query.eq("coupon_id", couponId);
                query.eq("product_id", cartPromotionItem.getProductId());
                SmsCouponProductRelation smsCouponProductRelation = smsCouponProductRelationMapper.selectOne(query);
                if (smsCouponProductRelation != null) {
                    newCartPromotionItemList.add(cartPromotionItem);
                }
            }
            for (OmsCartItem cartPromotionItem : newCartPromotionItemList) {
                totalAmount = totalAmount.add(cartPromotionItem.getPrice().multiply(new BigDecimal(cartPromotionItem.getQuantity())));
            }
            for (OmsCartItem omsCartItem : newCartPromotionItemList) {
                BigDecimal promotionPrice = omsCartItem.getPrice().multiply(new BigDecimal(omsCartItem.getQuantity())).divide(totalAmount, 2, BigDecimal.ROUND_DOWN);
                totalPromotionPrice = promotionPrice.add(totalPromotionPrice);
            }
            return totalPromotionPrice;
        } else if (smsCoupon.getUseType().equals(3)) {// 指定店铺
            List<OmsCartItem> newCartPromotionItemList = new ArrayList<>(); // 有优惠券
            for (OmsCartItem cartPromotionItem : cartPromotionItemList) {
                // 查询商品
                QueryWrapper<SmsCouponStoreRelation> query = new QueryWrapper();
                query.select("id");
                query.eq("coupon_id", couponId);
                query.eq("store_id", cartPromotionItem.getStoreId());
                SmsCouponStoreRelation smsCouponStoreRelation = couponStoreRelationMapper.selectOne(query);
                if (smsCouponStoreRelation != null) {
                    newCartPromotionItemList.add(cartPromotionItem);
                }
            }
            for (OmsCartItem cartPromotionItem : newCartPromotionItemList) {
                totalAmount = totalAmount.add(cartPromotionItem.getPrice().multiply(new BigDecimal(cartPromotionItem.getQuantity())));
            }
            for (OmsCartItem omsCartItem : newCartPromotionItemList) {
                BigDecimal promotionPrice = omsCartItem.getPrice().multiply(new BigDecimal(omsCartItem.getQuantity())).divide(totalAmount, 2, BigDecimal.ROUND_DOWN);
                totalPromotionPrice = promotionPrice.add(totalPromotionPrice);
            }
            return totalPromotionPrice;
        }
        return BigDecimal.ZERO;
    }

    /**
     *      * 判断时间是否在时间段内
     *      * 
     *      * @param nowTime
     *      * @param beginTime
     *      * @param endTime
     *      * @return
     *     
     */
    public static boolean belongCalendar(Date nowTime, Date beginTime, Date endTime) {
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);
        Calendar begin = Calendar.getInstance();
        begin.setTime(beginTime);
        Calendar end = Calendar.getInstance();
        end.setTime(endTime);
        if (date.after(begin) && date.before(end)) {
            return true;
        } else if (nowTime.compareTo(beginTime) == 0 || nowTime.compareTo(endTime) == 0) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 校验商品
     *
     * @param goods 商品
     * @param falg  标记
     * @param count 数量
     */
    private void checkGoods(PmsProduct goods, boolean falg, int count) {
        if (goods == null || goods.getId() == null) {
            throw new ApiMallPlusException("商品已删除");
        }
        if (falg && (goods.getStock() <= 0 || goods.getStock() < count)) {
            throw new ApiMallPlusException("库存不足!");
        }
    }

    /**
     * 校验库存商品
     *
     * @param goods 库存商品
     * @param count 数量
     */
    private void checkSkuGoods(PmsSkuStock goods, int count) {
        if (goods == null || goods.getId() == null) {
            throw new ApiMallPlusException("商品已删除");
        }
        if (goods.getStock() <= 0 || goods.getStock() < count) {
            throw new ApiMallPlusException("库存不足!");
        }
    }

    @Override
    public CommonResult generateStoreOrder(OrderParam orderParam) {
        if (ValidatorUtils.empty(orderParam.getTotal())) {
            orderParam.setTotal(1);
        }
        String type = orderParam.getType();
        UmsMember currentMember = memberService.getNewCurrentMember();

        // 1. 获取购物车商品
        List<OmsCartItem> cartPromotionItemList = new ArrayList<>();

        if (ValidatorUtils.empty(orderParam.getAddressId())) {
            return new CommonResult().failed("address is null");
        }
        //团购订单
        if (orderParam.getOrderType() == 3) {
            SmsGroupActivity smsGroupActivity = smsGroupActivityService.getById(orderParam.getGroupActivityId());
            if (ValidatorUtils.notEmpty(smsGroupActivity.getGoodsIds())) {
                List<PmsProduct> productList = (List<PmsProduct>) productService.listByIds(
                        Arrays.asList(smsGroupActivity.getGoodsIds().split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList()));
                if (productList != null && productList.size() > 0) {
                    //  order.setFreightAmount(smsGroupActivity.getTransfee());
                    //获取购物车信息
                    cartPromotionItemList = goodsToCartList(productList);
                }
            }
        } else {
            if ("3".equals(type)) { // 1 商品详情 2 勾选购物车 3全部购物车的商品
                cartPromotionItemList = cartItemService.listPromotion(currentMember.getId(), null);
            }
            if ("1".equals(type)) {
                Long cartId = Long.valueOf(orderParam.getCartId());
                OmsCartItem omsCartItem = cartItemService.selectById(cartId);
                List<OmsCartItem> list = new ArrayList<>();
                if (omsCartItem != null) {
                    list.add(omsCartItem);
                } else {
                    throw new ApiMallPlusException("订单已提交");
                }
                if (!CollectionUtils.isEmpty(list)) {
                    cartPromotionItemList = cartItemService.calcCartPromotion(list);
                }
            } else if ("2".equals(type)) {
                String cart_id_list1 = orderParam.getCartIds();
                String[] ids1 = cart_id_list1.split(",");
                List<Long> resultList = new ArrayList<>(ids1.length);
                for (String s : ids1) {
                    resultList.add(Long.valueOf(s));
                }
                cartPromotionItemList = cartItemService.listPromotion(currentMember.getId(), resultList);
                if (cartPromotionItemList == null || cartPromotionItemList.size() < 1) {
                    throw new ApiMallPlusException("没有下单的商品！");
                }

                BookOrder bookOrder1 = new BookOrder(orderParam, currentMember, cartPromotionItemList, null, false).invoke();
                if (bookOrder1.is())
                    return new CommonResult().failed("没有下单的商品");


                OmsOrder pidOrder = bookOrder1.order;
                List<OmsOrderItem> orderItemList = bookOrder1.orderItemList;
                Long pid = pidOrder.getId();
                String name = bookOrder1.getName();
                Map<String, Object> result = new HashMap<>();


                if (ValidatorUtils.empty(orderParam.getFormId())) {
                    push(currentMember, pidOrder, orderParam.getPage(), orderParam.getFormId(), name);
                }
                Map<Integer, List<OmsCartItem>> map = cartPromotionItemList.stream().collect(Collectors.groupingBy(OmsCartItem::getStoreId));
                if (map.size() > 1) {
                    for (Map.Entry<Integer, List<OmsCartItem>> entry : map.entrySet()) {
                        BookOrder bookOrder = new BookOrder(orderParam, currentMember, entry.getValue(), pid, true).invoke();
                        if (bookOrder.is())
                            return new CommonResult().failed("没有下单的商品");
                    }
                }
                result.put("order", pidOrder);
                result.put("orderItemList", orderItemList);
                return new CommonResult().success("下单成功", result);
            } else if ("6".equals(type)) { // 秒杀
                SmsFlashPromotionProductRelation relation = smsFlashPromotionProductRelationService.getById(orderParam.getSkillId());
                PmsProduct product = productService.getById(relation.getProductId());
                OmsCartItem omsCartItem = new OmsCartItem();
                omsCartItem.setQuantity(orderParam.getTotal());
                if (orderParam.getTotal() > relation.getFlashPromotionLimit()) {
                    throw new ApiMallPlusException("超过秒杀个数！");
                }
                omsCartItem.setPrice(relation.getFlashPromotionPrice());
                omsCartItem.setProductBrand(product.getBrandId() + "");
                omsCartItem.setProductCategoryId(product.getProductCategoryId());
                omsCartItem.setProductName(product.getName());
                omsCartItem.setProductPic(product.getPic());
                omsCartItem.setProductId(product.getId());
                omsCartItem.setChecked(1);
                omsCartItem.setProductSn(product.getProductSn());

                cartPromotionItemList.add(omsCartItem);
            }
        }

        BookOrder bookOrder = new BookOrder(orderParam, currentMember, cartPromotionItemList, null, false).invoke();
        if (bookOrder.is())
            return new CommonResult().failed("没有下单的商品");
        List<OmsOrderItem> orderItemList = bookOrder.getOrderItemList();
        OmsOrder order = bookOrder.order;
        String name = bookOrder.getName();
        Map<String, Object> result = new HashMap<>();
        result.put("order", order);
        result.put("orderItemList", orderItemList);

        if (ValidatorUtils.empty(orderParam.getFormId())) {
            push(currentMember, order, orderParam.getPage(), orderParam.getFormId(), name);
        }

        return new CommonResult().success("下单成功", result);
    }

    @Override
    public Object applyRe(String items) {
        ApplyRefundVo itemss = JsonUtils.fromJson(items, ApplyRefundVo.class);

        try {
            OmsOrderItem item = orderItemService.getById(itemss.getItemId());
            OmsOrderReturnApply apply = new OmsOrderReturnApply();
            UmsMember member = memberService.getNewCurrentMember();
            apply.setStatus(1);
            apply.setCreateTime(new Date());
            apply.setReturnAmount(item.getRealAmount());
            apply.setDescription(itemss.getDesc());
            apply.setOrderId(item.getOrderId());
            apply.setMemberUsername(member.getUsername());
            apply.setProductAttr(item.getProductAttr());
            apply.setProductCount(item.getProductQuantity());
            apply.setProductId(item.getProductId());
            apply.setProductName(item.getProductName());
            apply.setProductPic(item.getProductPic());
            apply.setProductPrice(item.getProductPrice());
            apply.setProductRealPrice(item.getRealAmount());
            apply.setProofPics(org.apache.commons.lang3.StringUtils.join(itemss.getImages(), ","));
            apply.setReason(itemss.getDesc());
            apply.setReturnPhone(member.getPhone());
            apply.setReturnName(member.getNickname());
            orderReturnApplyMapper.insert(apply);
            /*OmsOrderOperateHistory history = updateOrderInfo(id, order, OrderStatus.REFUNDING);
            history.setOrderStatus(OrderStatus.REFUNDING.getValue());
            history.setNote("申请退款");
            orderOperateHistoryService.save(history);*/
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new CommonResult().success();
    }

    private class BookOrder {
        private Long pid;
        private Boolean flagStore;
        private boolean myResult;
        private OrderParam orderParam;
        private UmsMember currentMember;
        private OmsOrder order;
        private List<OmsCartItem> cartPromotionItemList;

        private List<OmsOrderItem> orderItemList;
        private String name;

        public BookOrder(OrderParam orderParam, UmsMember currentMember, List<OmsCartItem> cartPromotionItemList, Long pid, Boolean flagStore) {
            this.orderParam = orderParam;
            this.currentMember = currentMember;
            this.cartPromotionItemList = cartPromotionItemList;
            this.pid = pid;
            order = new OmsOrder();
            this.flagStore = flagStore;

        }

        boolean is() {
            return myResult;
        }

        public List<OmsOrderItem> getOrderItemList() {
            return orderItemList;
        }

        public String getName() {
            return name;
        }

        public BookOrder invoke() {
            if (cartPromotionItemList == null || cartPromotionItemList.size() < 1) {
                myResult = true;
                return this;
            }
            orderItemList = new ArrayList<>();
            //获取购物车及优惠信息
            name = "";
            BigDecimal transFee = BigDecimal.ZERO;
            List<OmsCartItem> newCartItemList = new ArrayList<>();
            Integer isFirst = 1;
            Integer storeId = 0;
            String storeName = null;
            // 2. 校验商品库存，舍弃商品不存或没有库存 计算运费
            for (OmsCartItem cartPromotionItem : cartPromotionItemList) {
                boolean flag = false;
                PmsProduct goods = productService.getById(cartPromotionItem.getProductId());
                if (!ValidatorUtils.empty(cartPromotionItem.getProductSkuId()) && cartPromotionItem.getProductSkuId() > 0) {
                    if (goods != null && goods.getId() != null && goods.getStock() > 0 && goods.getStock() > cartPromotionItem.getQuantity()) {
                        PmsSkuStock skuStock = skuStockMapper.selectById(cartPromotionItem.getProductSkuId());
                        if (skuStock.getStock() > 0 && skuStock.getStock() >= cartPromotionItem.getQuantity()) {
                            flag = true;
                        }
                    }
                } else {
                    if (goods != null && goods.getId() != null && goods.getStock() > 0 && goods.getStock() >= cartPromotionItem.getQuantity()) {
                        flag = true;
                    }
                }
                if (flag) {
                    if (ValidatorUtils.notEmpty(pid)) {
                        if (goods.getTransfee().compareTo(transFee) > 0) {
                            transFee = goods.getTransfee();
                        }
                    }
                    //生成下单商品信息
                    OmsOrderItem orderItem = createOrderItem(cartPromotionItem);

                    orderItem.setType(AllEnum.OrderItemType.GOODS.code());
                    orderItemList.add(orderItem);
                    if (isFirst == 1) {
                        storeId = cartPromotionItem.getStoreId();
                        storeName = cartPromotionItem.getStoreName();
                        name = cartPromotionItem.getProductName();
                        order.setGoodsId(cartPromotionItem.getProductId());
                        order.setGoodsName(cartPromotionItem.getProductName());
                    }

                    newCartItemList.add(cartPromotionItem);
                }
            }
            if (ValidatorUtils.empty(pid)) {
                BigDecimal transFee1 = BigDecimal.ZERO;
                Map<Integer, List<OmsCartItem>> map = cartPromotionItemList.stream().collect(Collectors.groupingBy(OmsCartItem::getStoreId));
                if (map.size() > 1) {
                    for (Map.Entry<Integer, List<OmsCartItem>> entry : map.entrySet()) {
                        List<OmsCartItem> list = entry.getValue();
                        for (OmsCartItem cartPromotionItem : list) {
                            PmsProduct goods = productService.getById(cartPromotionItem.getProductId());
                            if (goods.getTransfee().compareTo(transFee1) > 0) {
                                transFee1 = goods.getTransfee();
                            }
                        }
                        transFee = transFee.add(transFee1);

                    }
                }
            }
            if (newCartItemList == null || newCartItemList.size() < 1) {
                myResult = true;
                return this;
            }

            //3.计算优惠券
            SmsCouponHistory couponHistory = null;
            SmsCoupon coupon = null;
            if (orderParam.getCouponId() != null) {
                couponHistory = couponHistoryService.getById(orderParam.getMemberCouponId());
                coupon = couponService.getById(orderParam.getCouponId());
            }
            UmsMemberReceiveAddress address = addressService.getById(orderParam.getAddressId());
            //根据商品合计、运费、活动优惠、优惠券、积分计算应付金额

            createOrderObj(order, orderParam, currentMember, orderItemList, address);
            if (orderParam.getOrderType() != 3) {
                order.setFreightAmount(transFee);
            }
            if (orderParam.getCouponId() == null || orderParam.getCouponId() == 0) {
                order.setCouponAmount(new BigDecimal(0));
            } else {
                order.setCouponId(orderParam.getCouponId());
                order.setCouponAmount(coupon.getAmount());
            }
            //获取积分使用规则
       /* UmsIntegrationConsumeSetting integrationConsumeSetting = integrationConsumeSettingMapper.selectOne(new QueryWrapper<>());

        if (integrationConsumeSetting!=null && currentMember.getIntegration()>0){
            order.setUseIntegration(currentMember.getIntegration()*integrationConsumeSetting.getMaxPercentPerOrder()/100);
            order.setIntegrationAmount(BigDecimal.valueOf((currentMember.getIntegration()*integrationConsumeSetting.getMaxPercentPerOrder()/100/integrationConsumeSetting.getDeductionPerAmount())));
        }*/

            /*CartMarkingVo vo = new CartMarkingVo();
            vo.setCartList(newCartItemList);
            SmsBasicMarking basicMarking = basicMarkingService.matchOrderBasicMarking(vo);
            log.info("basicMarking=" + com.alibaba.fastjson.JSONObject.toJSONString(basicMarking));
            if (basicMarking != null) {
                order.setPromotionAmount(basicMarking.getMinAmount());
            }

            if (ValidatorUtils.notEmpty(orderParam.getBasicGiftsVar())) {
                String[] basicGiftsList = orderParam.getBasicGiftsVar().split("@");
                if (basicGiftsList != null && basicGiftsList.length > 0) {
                    for (String basicGifts : basicGiftsList) {
                        if (ValidatorUtils.notEmpty(basicGifts)) {
                            String[] beanKv = basicGifts.split(":");
                            if (beanKv != null && beanKv.length > 1) {
                                String[] ids = beanKv[1].split(",");
                                if (ids != null && ids.length > 0) {
                                    for (String id : ids) {
                                        PmsGifts pmsGifts = pmsGiftsService.getById(id);
                                        if (pmsGifts != null) {
                                            OmsOrderItem orderItem = new OmsOrderItem();
                                            orderItem.setOrderSn(beanKv[0]);
                                            orderItem.setProductId(pmsGifts.getId());
                                            orderItem.setProductName(pmsGifts.getTitle());
                                            orderItem.setProductPic(pmsGifts.getIcon());
                                            orderItem.setProductPrice(pmsGifts.getPrice());
                                            orderItem.setProductQuantity(1);
                                            orderItem.setType(AllEnum.OrderItemType.GIFT.code());
                                            orderItemList.add(orderItem);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }*/

            order.setPayAmount(calcPayAmount(order));
            if (order.getPayAmount().compareTo(BigDecimal.ZERO) < 0) {
                order.setPayAmount(new BigDecimal("0.01"));
            }
            // TODO: 2018/9/3 bill_*,delivery_*
            if (pid != null) {
                order.setPid(pid);
            }
            if (flagStore) {
                order.setStoreId(storeId);
                order.setStoreName(storeName);
            }
            //插入order表和order_item表
            orderService.save(order);
            for (OmsOrderItem orderItem : orderItemList) {
                if (flagStore) {
                    orderItem.setStoreId(storeId);
                }
                orderItem.setOrderId(order.getId());
                orderItem.setOrderSn(order.getOrderSn());
                if (ValidatorUtils.notEmpty(orderParam.getSkillId())) {
                    orderItem.setGiftIntegration(orderParam.getSkillId().intValue());
                }
            }
            orderItemService.saveBatch(orderItemList);

            //如使用优惠券更新优惠券使用状态
            if (orderParam.getCouponId() != null && orderParam.getCouponId() > 0) {
                couponHistory.setUseStatus(1);
                couponHistory.setUseTime(new Date());
                couponHistory.setOrderId(order.getId());
                couponHistory.setOrderSn(order.getOrderSn());
                couponHistoryService.updateById(couponHistory);
            }
            OmsOrderOperateHistory history = new OmsOrderOperateHistory();
            history.setOrderId(order.getId());
            history.setCreateTime(new Date());
            history.setOperateMan("shop");
            history.setPreStatus(-1);
            history.setOrderStatus(OrderStatus.INIT.getValue());
            history.setNote("创建订单");
            orderOperateHistoryService.save(history);

            //如使用积分需要扣除积分
            if (order.getUseIntegration() != null) {
                memberService.updateIntegration(currentMember.getId(), currentMember.getIntegration() - order.getUseIntegration());
            }
            if (pid == null) {
                lockStockByOrder(orderItemList, orderParam.getType());
                //删除购物车中的下单商品
                deleteCartItemList(cartPromotionItemList, currentMember);
            }
            myResult = false;
            return this;
        }

    }

    /**
     * 商品详情
     *
     * @param orderParam
     * @return
     */
    @Override
    public OrderPayPageInfo generateOrderV2(GenerateOrderParam orderParam) {
        String totalOrderSn = ODDGenerator.getD(StringUtils.replace(UUID.randomUUID().toString(), "-", ""));// 生成总订单号
        Long couponId = null;
        // 优惠券领取参数-数组
        String storeMemberCouponId = orderParam.getStoreMemberCouponId();
        JSONArray storeMemberCouponIdArray = JSONArray.parseArray(storeMemberCouponId);
        if (storeMemberCouponIdArray != null && storeMemberCouponIdArray.size() != 0) {
            JSONObject obj1 = storeMemberCouponIdArray.getJSONObject(0);
            orderParam.setMemberCouponId(obj1.getLong("memberCouponId"));
            SmsCouponHistory smsCouponHistory = couponHistoryService.getById(obj1.getLong("memberCouponId"));
            orderParam.setCouponId(smsCouponHistory.getCouponId());
            couponId = smsCouponHistory.getCouponId();
        }

        // 校验参数
        if (ValidatorUtils.empty(orderParam.getTotal()))

        {
            orderParam.setTotal(1);
        }
        if (ValidatorUtils.empty(orderParam.getMemberId()))

        {
            throw new ApiMallPlusException("用户参数不能为空");
        }

        UmsMember currentMember = memberService.getById(orderParam.getMemberId());
        if (ValidatorUtils.empty(orderParam.getAddressId()))

        {
            throw new ApiMallPlusException("地址参数不能为空");
        }

        // 查询购物车信息
        OmsCartItem omsCartItem;
        String cartId = orderParam.getCartIds().split(",")[0];
        if (org.apache.commons.lang.StringUtils.isBlank(cartId))

        {
            throw new ApiMallPlusException("下单参数不能为空");
        }

        omsCartItem = cartItemService.selectById(Long.valueOf(cartId));
        if (omsCartItem == null)

        {
            throw new ApiMallPlusException("订单已提交");
        }

        List<OmsCartItem> cartPromotionItemList = new ArrayList<>();
        cartPromotionItemList.add(omsCartItem);
        // 校验商品库存，舍弃商品不存在或没有库存 计算运费
        List<OmsOrderItem> orderItemList = new ArrayList<>();
        List<OmsCartItem> newCartItemList = new ArrayList<>();

        for (OmsCartItem cartPromotionItem : cartPromotionItemList) {
            boolean flag = false;
            PmsProduct goods = productService.getById(cartPromotionItem.getProductId());
            if (!ValidatorUtils.empty(cartPromotionItem.getProductSkuId()) && cartPromotionItem.getProductSkuId() > 0) {
                if (goods != null && goods.getId() != null && goods.getStock() > 0 && goods.getStock() > cartPromotionItem.getQuantity()) {
                    PmsSkuStock skuStock = skuStockMapper.selectById(cartPromotionItem.getProductSkuId());
                    if (skuStock.getStock() > 0 && skuStock.getStock() >= cartPromotionItem.getQuantity()) {
                        flag = true;
                    }
                }
            } else {
                if (goods != null && goods.getId() != null && goods.getStock() > 0 && goods.getStock() >= cartPromotionItem.getQuantity()) {
                    flag = true;
                }
            }
            // 可以
            if (flag) {
                newCartItemList.add(cartPromotionItem);
            }
        }
        if (newCartItemList == null || newCartItemList.size() < 1)

        {
            throw new ApiMallPlusException("订单已提交");
        }
        //生成下单商品信息
        for (
                OmsCartItem cartPromotionItem : newCartItemList)

        {
            BigDecimal realAmount = this.getOmsOrderItemRealAmount(cartPromotionItemList, cartPromotionItem, couponId);
            //生成下单商品信息
            OmsOrderItem orderItem = createOrderItemV1(cartPromotionItem);
            orderItem.setType(AllEnum.OrderItemType.GOODS.code());
            orderItem.setRealAmount(realAmount);
            orderItemList.add(orderItem);
        }

        // 计算运费
        BigDecimal transFee = this.getOrderTransFee(newCartItemList);
        OmsOrder order = new OmsOrder();
        order.setFreightAmount(transFee);  // 运费
        order.setTotalOrderSn(totalOrderSn);
        //计算优惠券
        SmsCouponHistory couponHistory = new SmsCouponHistory();
        SmsCoupon coupon = null;
        if (orderParam.getCouponId() != null)

        {
            coupon = couponService.getById(orderParam.getCouponId());
        }

        UmsMemberReceiveAddress address = addressService.getById(orderParam.getAddressId());

        //5、根据商品合计、运费、活动优惠、优惠券计算应付金额
        order = createOrderObjV1(order, orderParam, currentMember, orderItemList, address, coupon, newCartItemList);
        log.info("订单支付金额222：" + order.getPayAmount());
        // 调用远程下单接口
//        this.doRemotecreateOrder(currentMember, orderItemList, order);
        //插入order表和order_item表
        orderService.save(order);
        orderItemService.saveBatch(orderItemList);
        //如使用优惠券更新优惠券使用状态
        if (orderParam.getCouponId() != null && orderParam.getCouponId() > 0)

        {
            couponHistory.setId(orderParam.getMemberCouponId());
            couponHistory.setUseStatus(1);
            couponHistory.setUseTime(new Date());
            couponHistory.setOrderId(order.getId());
            couponHistory.setOrderSn(order.getOrderSn());
            couponHistoryService.updateById(couponHistory);
        }

        // 订单操作记录
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(order.getId());
        history.setCreateTime(new

                Date());
        history.setOperateMan("shop");
        history.setPreStatus(-1);
        history.setOrderStatus(OrderStatus.INIT.getValue());
        history.setNote("创建订单");
        orderOperateHistoryService.save(history);

        // 锁库存，核心业务逻辑
        lockStockByOrderV1(orderItemList);

        // 删除购物车中的临时商品
        List<Long> ids = new ArrayList<>();
        for (
                OmsCartItem cartPromotionItem : cartPromotionItemList)

        {
            ids.add(cartPromotionItem.getId());
        }
        cartItemService.delete(currentMember.getId(), ids);
        // 封装结果
        OrderPayPageInfo result = new OrderPayPageInfo();
        result.setOrderSubmitTime(System.currentTimeMillis());
        result.setPayAmount(order.getPayAmount());
        result.setPaymentList(paymentsService.list(new QueryWrapper<OmsPayments>().eq("status", 1)));
        result.setTotalOrderSn(totalOrderSn);

        return result;
    }

    /**
     * 调用远程创建订单接口
     *
     * @param currentMember
     * @param orderItemList
     * @param order
     */
    private void doRemotecreateOrder(UmsMember currentMember, List<OmsOrderItem> orderItemList, OmsOrder order) {
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//        List<Map<String, Object>> list = new ArrayList<>();
//        for (int i = 0; i < orderItemList.size(); i++) {
//            // 封装下单的参数
//            OmsOrderItem obj = orderItemList.get(i);
//            Map<String, Object> orderDetailsMap = new HashMap<>();
//            orderDetailsMap.put("id", obj.getProductId());
//            orderDetailsMap.put("name", obj.getProductName());
//            orderDetailsMap.put("photoUrl", obj.getProductPic());
//            orderDetailsMap.put("price", obj.getProductPrice());
//            orderDetailsMap.put("number", obj.getProductQuantity());
//            orderDetailsMap.put("creationTime", sdf.format(System.currentTimeMillis()));
//            orderDetailsMap.put("stock", "");
//            orderDetailsMap.put("gift", "");
//            orderDetailsMap.put("describe", obj.getProductAttr()); // 规格
//            list.add(orderDetailsMap);
//        }
//        log.info("商品信息：" + JSON.toJSON(list).toString());
//        Map<String, String> orderMap = new HashMap<>();
//        orderMap.put("userId", currentMember.getId().toString());
//        orderMap.put("businesSpecies", "S");
//        orderMap.put("orderAllPrice", order.getPayAmount().toString());
//        orderMap.put("goodsSn", null);
//        orderMap.put("goodsJson", JSON.toJSON(list).toString());// 商品列表信息
//        orderMap.put("freeOrder", "2"); // 不免费
//        String ORDER_URL = this.newCreatePublicOrdersUrl;
//        String s = HttpClientsUtil.httpPostBody(ORDER_URL, 10000, orderMap, "utf-8");
//        // 解析返回结果
//        JSONObject pareseJSON = JSONObject.parseObject(s);
//        if (pareseJSON.getString("code").equals("0")) {
//            // 返回订单号
//            String orderNo = pareseJSON.get("data").toString();
//            order.setTotalOrderSn(orderNo);
//            //6、插入order表和order_item表
//            orderService.save(order);
//            orderItemService.saveBatch(orderItemList);
//            // 提交成功
//        } else {
//            throw new ApiMallPlusException("订单提交失败！");
//        }
        // 返回订单号
        String orderNo = generateOrderSn(order);
        order.setTotalOrderSn(orderNo);
        //6、插入order表和order_item表
        orderService.save(order);
        orderItemService.saveBatch(orderItemList);
    }

    /**
     * 计算运费:核心业务逻辑
     * 同一运费模板/不同运费模板
     *
     * @param newCartItemList
     * @return
     */
    private BigDecimal getOrderTransFee(List<OmsCartItem> newCartItemList) {
        List<BigDecimal> transfeeList = new ArrayList<>();
        BigDecimal transfee1 = BigDecimal.ZERO;
        for (OmsCartItem omsCartItem : newCartItemList) {
            // 获取商品信息
            PmsProduct pmsProduct = pmsProductMapper.selectById(omsCartItem.getProductId());
            // 获取运费
            BigDecimal transfee2 = pmsProduct.getTransfee();
            if (transfee2 == null) { // 没有填运费
                // 获取运费模板
                PmsFeightTemplate pmsFeightTemplate = pmsFeightTemplateMapper.selectById(pmsProduct.getFeightTemplateId());
                if (pmsFeightTemplate.getChargeType().equals(0)) {// 按照重量
                    BigDecimal price = BigDecimal.ZERO;
                    // 首重
                    BigDecimal firstWeight = price.add(pmsFeightTemplate.getFirstFee());  // +
                    BigDecimal hasWeight = pmsProduct.getWeight().subtract(firstWeight); // -
                    transfee2 = hasWeight.divide(pmsFeightTemplate.getContinueWeight()).multiply(pmsFeightTemplate.getContinmeFee()); // *
                } else { // 按照件数
                    transfee2 = pmsFeightTemplate.getFirstFee().multiply(new BigDecimal(omsCartItem.getQuantity()));
                }
            }
            transfeeList.add(transfee2);
        }
        // 排序
        Collections.sort(transfeeList);
        // 填运费，优先使用这个
        if (transfeeList.size() > 0) {
            // 同一家的商品运费取最低的
            transfee1 = transfeeList.get(0);
        }
        return transfee1;
    }

    /**
     * 购物车
     *
     * @param orderParam
     * @return
     */
    @Override
    public OrderPayPageInfo generateOrderV3(GenerateOrderParam orderParam) {
        // 优惠券领取参数
        Map<String, String> storeMemberCouponIdMap = new HashedMap();
        // 优惠券参数
        Map<String, String> storeCouponIdMap = new HashedMap();
        // 优惠券领取参数-数组
        String storeMemberCouponId = orderParam.getStoreMemberCouponId();
        JSONArray storeMemberCouponIdArray = JSONArray.parseArray(storeMemberCouponId);
        if (storeMemberCouponIdArray != null && storeMemberCouponIdArray.size() != 0) {
            JSONObject obj1 = storeMemberCouponIdArray.getJSONObject(0);
            SmsCouponHistory smsCouponHistory = couponHistoryService.getById(obj1.getLong("memberCouponId"));
            storeMemberCouponIdMap.put(obj1.getLong("storeId").toString(), obj1.getLong("memberCouponId").toString());
            storeCouponIdMap.put(obj1.getLong("storeId").toString(), smsCouponHistory.getCouponId().toString());
        }
        // 总订单号
        String totalOrderSn = ODDGenerator.getD(StringUtils.replace(UUID.randomUUID().toString(), "-", ""));
        // 1、校验参数
        if (ValidatorUtils.empty(orderParam.getTotal())) {
            orderParam.setTotal(1);
        }
        if (ValidatorUtils.empty(orderParam.getMemberId())) {
            throw new ApiMallPlusException("memberId参数为空");
        }
        UmsMember currentMember = memberService.getById(orderParam.getMemberId());
        if (ValidatorUtils.empty(orderParam.getAddressId())) {
            throw new ApiMallPlusException("AddressId参数为空");
        }
        // 2、查询购物车信息
        // 查询购物车信息
        String cartIds = orderParam.getCartIds();
        if (org.apache.commons.lang.StringUtils.isBlank(cartIds)) {
            throw new ApiMallPlusException("cartIds参数为空");
        }
        List<OmsCartItem> cartPromotionItemList;
        // 开始查询购物车商品信息
        String cart_id_list1 = orderParam.getCartIds();
        if (org.apache.commons.lang.StringUtils.isBlank(cart_id_list1)) {
            throw new ApiMallPlusException("参数为空");
        }
        String[] ids1 = cart_id_list1.split(",");
        List<Long> resultList = new ArrayList<>(ids1.length);
        for (String s : ids1) {
            resultList.add(Long.valueOf(s));
        }
        cartPromotionItemList = cartItemService.list(currentMember.getId(), resultList);
        if (cartPromotionItemList == null || cartPromotionItemList.size() < 1) {
            throw new ApiMallPlusException("订单已提交");
        }
        // 分店铺
        LinkedHashMap<String, List<OmsCartItem>> map = groupListBySeq(cartPromotionItemList);
        BigDecimal totalPayAmount = BigDecimal.ZERO;
        log.info("订单111：" + map);
        //遍历集合
        for (Map.Entry<String, List<OmsCartItem>> entry : map.entrySet()) {
            List<OmsCartItem> omsCartItems = entry.getValue();
            // 校验商品库存，舍弃商品不存在或没有库存 计算运费
            List<OmsOrderItem> orderItemList = new ArrayList<>();
            //生成下单商品列表
            for (OmsCartItem cartPromotionItem : omsCartItems) {
                BigDecimal realAmount = this.getOmsOrderItemRealAmount(cartPromotionItemList, cartPromotionItem, orderParam.getCouponId());
                //生成下单商品信息
                OmsOrderItem orderItem = createOrderItemV1(cartPromotionItem);
                orderItem.setType(AllEnum.OrderItemType.GOODS.code());
                orderItem.setRealAmount(realAmount);
                orderItemList.add(orderItem);
            }
            // 计算运费
            BigDecimal transFee = this.getOrderTransFee(omsCartItems);
            OmsOrder order = new OmsOrder();
            order.setFreightAmount(transFee);     // 运费
            order.setTotalOrderSn(totalOrderSn); // 总订单号
            //4.计算优惠券
            SmsCouponHistory couponHistory = new SmsCouponHistory();
            SmsCoupon coupon = null;
            orderParam.setCouponId(Long.parseLong(storeCouponIdMap.get(entry.getKey().toString())));
            if (orderParam.getCouponId() != null && !orderParam.getCouponId().equals(0)) {
                coupon = couponService.getById(orderParam.getCouponId());
            }
            UmsMemberReceiveAddress address = addressService.getById(orderParam.getAddressId());
            //5、根据商品合计、运费、活动优惠、优惠券计算应付金额
            order = createOrderObjV1(order, orderParam, currentMember, orderItemList, address, coupon, omsCartItems);
            // 应付金额
            totalPayAmount = totalPayAmount.add(order.getPayAmount());
            //6、插入order表和order_item表
            orderService.save(order);
            orderItemService.saveBatch(orderItemList);
            // 优惠券领取id
            orderParam.setMemberCouponId(Long.parseLong(storeMemberCouponIdMap.get(entry.getKey().toString())));
            //7、如使用优惠券更新优惠券使用状态
            if (orderParam.getCouponId() != null && orderParam.getCouponId() > 0) {
                couponHistory.setId(orderParam.getMemberCouponId());
                couponHistory.setUseStatus(1);
                couponHistory.setUseTime(new Date());
                couponHistory.setOrderId(order.getId());
                couponHistory.setOrderSn(order.getOrderSn());
                couponHistoryService.updateById(couponHistory);
            }
            // 8、订单操作记录
            OmsOrderOperateHistory history = new OmsOrderOperateHistory();
            history.setOrderId(order.getId());
            history.setCreateTime(new Date());
            history.setOperateMan("shop");
            history.setPreStatus(-1);
            history.setOrderStatus(OrderStatus.INIT.getValue());
            history.setNote("创建订单");
            orderOperateHistoryService.save(history);

            // 9、锁库存
            lockStockByOrderV1(orderItemList);
            // 10、删除购物车中的下单商品
            List<Long> ids = new ArrayList<>();
            for (OmsCartItem cartPromotionItem : cartPromotionItemList) {
                ids.add(cartPromotionItem.getId());
            }
            cartItemService.delete(currentMember.getId(), ids);
        }
        // 封装结果
        OrderPayPageInfo result = new OrderPayPageInfo();
        result.setOrderSubmitTime(System.currentTimeMillis());
        result.setPayAmount(totalPayAmount);
        result.setPaymentList(paymentsService.list(new QueryWrapper<OmsPayments>().eq("status", 1)));
        result.setTotalOrderSn(totalOrderSn);
        return result;
    }

    /**
     * 锁定下单商品的所有库存
     */
    public void lockStockByOrderV1(List<OmsOrderItem> cartPromotionItemList) {
        log.info("lockStockByOrder");
        for (OmsOrderItem item : cartPromotionItemList) {
            log.info("商品类型：" + item.getType());
            log.info("商品信息：" + item);
            PmsProduct goods = productService.getById(item.getProductId());
            if (goods != null && goods.getId() != null) {
                PmsProduct newGoods = new PmsProduct();
                newGoods.setId(goods.getId());
                redisService.remove(String.format(Rediskey.GOODSDETAIL, goods.getId() + ""));
                if (!ValidatorUtils.empty(item.getProductSkuId()) && item.getProductSkuId() > 0) {
                    PmsSkuStock skuStock = skuStockMapper.selectById(item.getProductSkuId());
                    if ((skuStock.getStock() - item.getProductQuantity()) < 0) {
                        // 库存不足
                        throw new ApiMallPlusException("goods is stock out. goodsId=" + item.getProductId() + ", skuId=" + item.getProductSkuId());
                    } else {
                        skuStock.setId(item.getProductSkuId());
                        skuStock.setStock(skuStock.getStock() - item.getProductQuantity()); // 库存减
                        skuStockMapper.updateById(skuStock);
                    }
                } else {
                    if ((goods.getStock() - item.getProductQuantity()) < 0) {
                        // 库存不足
                        throw new ApiMallPlusException("goods is stock out. goodsId=" + item.getProductId() + ", goodsId=" + item.getProductSkuId());
                    }
                }
                newGoods.setSale(goods.getSale() + item.getProductQuantity());
                newGoods.setStock(goods.getStock() - item.getProductQuantity());// 库存减
                productService.updateById(newGoods);
            }
        }
    }

}
